I have many files with different names that end with txt
.
rtfgtq56.txt
fgutr567.txt
..
So I am running this command
for i in *txt
do
awk -F "\t" '{print $2}' $i | grep "K" | awk '{print}' ORS=';' | awk -F "\t" '{OFS="\t"; print $i, $1}' > ${i%.txt*}.k
done
My problem is that I want to add the name of every file in the first column, so I run this part:
awk -F "\t" '{OFS="\t"; print $i, $1}' > ${i%.txt*}
$i
means the file that are in the for loop,
but it did not work because awk can't read the $i
in the for loop.
Do you know how I can solve it?
CodePudding user response:
You want to refactor eveything into a single Awk script anyway, and take care to quote your shell variables.
for i in *.txt
do
awk -F "\t" '/K/{a = a ";" $2}
END { print FILENAME, substr(a, 1) }' "$i" > "${i%.txt*}.k"
done
... assuming I untangled your logic correctly. The FILENAME
Awk variable contains the current input file name.
More generally, if you genuinely want to pass a variable from a shell script to Awk, you can use
awk -v awkvar="$shellvar" ' .... # your awk script here
# Use awkwar to refer to the Awk variable'
Perhaps see also useless use of grep
.
CodePudding user response:
Using the -v
option of awk
, you can create an awk Variable based on a shell variable.
awk -v i="$i" ....
Another possibility would be to make i
an environment variable, which means that awk can access it via the predefined ENVIRON
array, i.e. as ENVIRON["i"]
.