BASH: if statement in a for loop
I am sure it is a very basic question, but I checked a lot of threads and could not find an answer.
For files in a directory, how to process them if their filename do NOT contain a pattern? I tried something like this so far: Code:
for A in /path/to/*.txt; do if [[ ls | grep -v \^pattern.\ ${A} ]] then; <command ${A}>; fi; done |
Quote:
Code:
for f in `ls [!pattern]*`; do echo "$f"; done |
Awesome ! Thanks Michael !
|
Quote:
Code:
for f in `ls /path/to/the/directory/[!file_pattern]*`; do echo "$f"; done But if you plan to re-use this under changing conditions, it will be interesting, how you compose your pattern each time. I am not really sure, but have a bad feeling about the negation. It may introduce more potential for false positives than without... Maybe it is wiser to move the unwanted files away from the directory, then just process the remainder... This is really strange; as if I had made some bad experience with such a match one time but cannot remember any more... |
Here's an alternate method that might be interesting to see. It's more like how my brain works, so (at least for me) it's more readable.
Code:
for FN in $(ls /path/to/*.txt | awk '!/pattern/'); do <command ${FN}>; done |
For both posts 2, 4 and 5 one will hope that none of the output of `` or $() is separated by white space, otherwise the command will be working on something that does not exist.
I have to say that from the original example provided I am not sure I understand the task? Code:
ls | grep -v \^pattern.\ ${A} any files or directories that would contain such a pattern? Are you able to perhaps explain, perhaps with example data, exactly what it is you are after? |
To handle files with spaces in the names, this variant should work.
Code:
ls /path/to/*.txt | awk '!/pattern/' | while read FN; do <command ${FN}>; done In my experience it will either work or break every time, so it's easy enough to test before you start using the script. But I still prefer to avoid that sort of construct where I can. |
Quote:
Code:
for f in [!pattern]*; do echo "$f"; done Quote:
If you enable extglob, !(pattern-list) gives you actual pattern negation. |
cnamejj's last post seems to make it clearer what is being attempted, but I still like to keep things simple:
Code:
pattern=<regex here> |
Quote:
Quote:
The original example lets much space for imagination. A temptation that I try to resist. ;) |
All times are GMT -5. The time now is 09:13 AM. |