• Uncategorized

About linux : for-each-pair-of-files-with-the-same-prefix-execute-code

Question Detail

I have a large list of directories, each of which contains a varied number of “paired” files. By paired, I mean the prefix is the same for two files, and the pairs are denoted as “a” and “b”. The prefix does not follow a defined pattern either. My broader intentions are to write a bash script that will list all subdirectories in a given directory, cd into each directory, find the pairs of files, and execute a function on the pairs. Here is an example directory:

Dir1
    123_a.txt
    234_a.txt
    123_b.txt
    234_b.txt

Dir2
    345_a.txt
    345_b.txt

Dir3
    456_a.txt
    567_a.txt
    678_a.txt
    456_b.txt
    567_b.txt
    678_b.txt

I can use this code to loop thought each directory:

for d in ./*/ ; do (cd "$d" && script.sh); done

In script.sh, I have been working on writing a script that will find all pairs of files (which is the problem I am struggling to figure out), and then call the function I want to apply to those files. This is the gist of what I have been trying:

for file in ./*_a.txt; do (find the paired file with *_b.txt && run_function.sh); done

Ive broken the problem into needing to get the value of “*” for the _a.txt files, and then searching the directory using this value for the matching _b.txt suffix,and making a subdirectory that I can put them into so I can then apply run_function.sh. So Dir1, would contain subdirectories 123 and 234.

Let me know if this doesn’t make sense. The part of the problem I’m struggling with is matching files without a defined prefix.

Thanks for your help.

Question Answer

Use parameter expansion:

#!/bin/bash
file=123_a.txt
prefix=${file%_a.txt}  # remove _a.txt from the right
second=${prefix}_b.txt
if [[ -f $second ]] ; then
    run_function "$file" "$second"
fi

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.