Generating links recursively and removing a substring from the filename

I recently encountered the following problem:

A folder contains a number of subdirectories, each with a large number of *.txt files. The filenames all contain dot-separated information regarding the files contents. Among other things, the file name contains a string describing a discount curve used for a calculation. It can be either of these strings: LIBOR 6M_HUF 1M_EUR 3M_EUR 3M_HUF 3M_CHF 6M_EUR 1M_USD 3M_RON 6M_CHF OI_EUR OI_CHF 6M_USD 3M_USD 1M_CHF 3M_CZK 6M_CZK 1M_CZK 3M_JPY 6M_JPY 12M_EUR 6M_PLN 3M_PLN 3M_RUB EURIBOR OI_USD MANUAL 12M_USD 3M_GBP 3M_TRY 3M_CAD. I needed to create links for all files such that this string is removed without changing anything else, i.e. the file dir/subdir1/test.file.3M_CAD.txt is linked from dir/subdir1/test.file..txt.

Here's how I did it in bash:

echo "LIBOR 6M_HUF 1M_EUR 3M_EUR 3M_HUF 3M_CHF 6M_EUR 1M_USD 3M_RON 6M_CHF OI_EUR OI_CHF 6M_USD 3M_USD 1M_CHF 3M_CZK 6M_CZK 1M_CZK 3M_JPY 6M_JPY 12M_EUR 6M_PLN 3M_PLN 3M_RUB EURIBOR OI_USD MANUAL 12M_USD 3M_GBP 3M_TRY 3M_CAD" > curves.txt
find . -type d > listdir.txt
dir=`pwd`
for c in `cat curves.txt`; do
    for d in `cat listdir.txt`; do 
        cd $d; 
        find . -maxdepth 1 -name "*$c*.txt" -exec bash -c 'ln -sf $0 ${0/'"$c"'/}' {} \;;
        cd $dir; 
    done;
    echo $c; 
done;
echo "Done."

Leave a Reply

Your email address will not be published. Required fields are marked *