0

I have a set of text files containing values and stored across several directories. I need to workout a command with loop, so that I can apply my command to each files in several directories.

The code I figured is

#!/bin/bash
#
dir=`pwd`
datapath1=$dir/datafiles1
datapath2-$dir/datafiles2

for file in /$datapath1/*.txt ; do 
   sort -k1,1rn < "$file"
done > file.cat &&
# 
for file in /$datapath2/*.txt ; do 
   sort -k1,1rn < "$file"
done > file.cat &&
#

clearly, this is very difficult in the case of many directories. Is there any simplified approach for this, possibly accommodate in a single loop?

0

There is a problem with your script: Each loop overwrites file.cat.

The problem can be eliminated and the script simplified if you loop over all files in a single loop.

#!/bin/bash

dir=$(pwd)
datapath1=$dir/datafiles1
datapath2=$dir/datafiles2

for file in "$datapath1"/*.txt "$datapath2"/*.txt; do 
   sort -k1,1rn < "$file"
done > file.cat

Also always quote your variables.


As noted by Kusalananda, if the directory names are very similar, it may be even possible to use a glob that addresses all directories and files involved. In the example given, that is indeed possible with

sort -k1,1rn "$PWD"/datafiles[12]/*.txt > file.cat
0

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.