0

I have a command that takes a file name as a variable, I have given it as a name pattern, file_*_123.txt

Script.sh file_*_123.txt

Now if there are more than one files with matching pattern it only executes for the first file, I want this script to be executed for each file matching the name pattern. for e.g. file_1_123.txt, file_2_123.txt, file_3_123.txt

Someone kind of for loop. However, because the number of file(s) can be 1 or more than 1 so not sure how to iterate through.

Can anyone please suggest a solution to it.

  • Check the man page for find, specifically the -exec option. – ivanivan Jul 17 '18 at 14:25
2

This would either involve calling your script in a loop, or arranging for your script to loop over its command line arguments.

The first option:

for filename in file_*_123.txt; do
    ./Script.sh "$filename"
done

This would call your script once for each file that matches the pattern file_*_123.txt.

The second option:

You would modify the script and wrap the body of it in a loop, such as

#!/bin/sh

for filename do
    # here you do whatever you need to do with "$filename"
done

or,

#!/bin/sh

for filename in "$@"; do
    # here you do whatever you need to do with "$filename"
done

(these two variants of the loop are equivalent)

This would cause the script to loop over its command line arguments. You would then run your script as you have shown in the question:

./Script.sh file_*_123.txt
| improve this answer | |
1

If you wanna execute these matched files in parallel, you may consider use utility parallel

code sample

funcXXXX(){
    file_path="${1}"
    /PATH/Script.sh "${file_path}"
}

# make function funcXXXX can be used by parallel
export -f funcXXXX

ls /PATH/file_*_123.txt | xargs -l | parallel -k -j 0 funcXXXX
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.