Abdel
Abdel

Reputation: 6106

awk: using escape characters in for statement

I have the following awk command which works perfectly:

awk 'BEGIN { ORS = " " } {print 22, $1, NR; for(i=2;i<=NF;++i) print $i}{print "\n"}' file

What it does is insert two columns: the value 22 as the first, and the nr of the row as the third (see this question). I tried running this command in a for loop as follows:

for p in 20 21 22
do
awk 'BEGIN { ORS = " " } {print $p, \$1, NR; for(i=2;i<=NF;++i) print \$i}{print "\n"}' file > file$p
done

So instead of the 22 in the first column, 3 files are made where each file has 20, 21 or 22 as the first column. Unfortunately, this doesn't work and I get the message: ^ backslash not last character on line. It probably has something to do with how I escaped the $ characters, but I don't know how else to do it... any ideas?

Upvotes: 0

Views: 971

Answers (2)

Eran Ben-Natan
Eran Ben-Natan

Reputation: 2615

You are in the right direction. Because your awk script is within ' (single quotes), bash doesn't replace $p with its value in the script (See Advanced Bash-Scripting Guide - Quoting). You need to do one of the following: 1 (Recommened):

for p in 20 21 22
do
awk -v p=$p 'BEGIN { ORS = " " } {print p, \$1, NR; for(i=2;i<=NF;++i) print \$i}{print "\n"}' file > file$p
done

2: Use " instead of ' and within the awk escape the " by \"

Upvotes: 2

Fredrik Pihl
Fredrik Pihl

Reputation: 45672

You can assign a shell-parameter to awk using

-v parameter=value

i.e. use

awk -v p=$p ...

Like this:

for p in 20 21 22
do
awk -v p=$p 'BEGIN { ORS = " " } [TOO LONG LINE]' file > file$p
done

Complete command:

for p in 20 21 22; do awk -v p=$p 'BEGIN { ORS = " " } {print p, $1, NR; for(i=2;i<=NF;++i) print $i}{print "\n"}' file > file$p; done

Upvotes: 2

Related Questions