Home > Blockchain >  automatice bash command for multiple files
automatice bash command for multiple files

Time:06-02

I have a directory with multiple files

file1_1.txt
file1_2.txt
file2_1.txt
file2_2.txt
...

And I need to run a command structured like this

command [args] file1 file2

So I was wondering if there was a way to call the command just one time on all the files, instead of having to call It each time on each pair of files.

CodePudding user response:

Use find and xargs, with sort, since the order appears meaningful in your case:

find . -name 'file?_?.txt' | sort | xargs -n2 command [args]

CodePudding user response:

If your command can take multiple pairs of files on the command line then it should be sufficient to run

command ... *_[12].txt

The files in expanded glob patterns (such as *_[12].txt) are automatically sorted so the files will be paired correctly.

If the command can only take one pair of files then it will need to be run multiple times to process all of the files. One way to do this automatically is:

for file1 in *_1.txt; do
    file2=${file1%_1.txt}_2.txt
    [[ -f $file2 ]] && echo command "$file1" "$file2"
done
  •  Tags:  
  • bash
  • Related