This is my first more-than-1-line script. It takes an input folder and a file prefix and gets all the matching files. For the first of the files, the script grabs the first line and appends an extra label string and puts that into $data
. For all files (including the first), it takes the second line, adds the timestamp found from the filename, and appends a that as new line to $data
. When it's done, it writes the output.
The problem is it's pretty slow. 1 directory might have 10,000 files. In that case, the script takes about 3-4 minutes to complete. When doing this over 10 such directories, it begins to get quite annoying.
So, I'm hoping someone here could help speed things up, preferably with explanations so I also get better.
for cs in {47..52}; do
csdirnm="CASE$cs";
tsdirnm="eta_at_x2";
label='flow-time';
dir="$csdirnm/$tsdirnm/";
files=$(ls -tr $dir); # -tr sort on time created, reversed (newest last).
i=0;
for f in $files ; do
fn=$dir$f;
if [[ $i = 0 ]]; then
data="$(sed -n 1p $fn) $label";
((i++));
fi
d=$(sed -n 2p $fn);
t=$(echo $fn | perl -pe 's|.*?(\d+\.\d+)|\1|');
data+="\n$d $t";
done;
echo -e "$data">"$csdirnm/${csdirnm}_${tsdirnm}_20T.time-series";
done;