How to apply the same awk action to different files?
You can apply the files in a for loop:
for file in *.tex;
do
awk 'ORS=NR%3?" ":"\n"' "$file" > "$(basename "$file")_sorted.tex"
done
Or on one line:
for file in *.tex; do awk 'ORS=NR%3?" ":"\n"' $file > "$(basename "$file" .tex)_sorted.tex"; done
Since you don't specify which shell, go with the more standard basename
instead using the shell specific syntax ${file%%.tex}
.
If you modify the awk
code, can be solved by a single awk
process and no shell loop:
awk 'FNR==1{if(o)close(o);o=FILENAME;sub(/\.tex/,"_sorted.tex",o)}{ORS=FNR%3?" ":"\n";print>o}' *.tex
Not a beauty, just insignificantly faster.
Explanations as requested in comment.
FNR
(file number or record) is similar to NR
(number or record), but while NR
is a continuous sequence number of all input records, FNR
is reset to 1 when processing of a new input file is started.
A gawk
4.0 only alternative for the FNR==1
is the BEGINFILE
special pattern.
awk '
FNR==1{ # first record of an input file?
if(o)close(o); # was previous output file? close it
o=FILENAME;sub(/\.tex/,"_sorted.tex",o) # new output file name
}
{
ORS=FNR%3?" ":"\n"; # set ORS based on FNR (not NR as in the original code)
print>o # print to the current output file
}
' *.tex