user595014
user595014

Reputation: 124

Awk command with command line unix shell script

awk -F, 'NR>1 && NR <10 {$8="abc";}1' OFS=, x.csv > y.csv

Above command is replacing 8th column of x.csv file to string abc for line number 1 to 10 successfully. But i want to pass starting line number (which is 1) with command line argument in shell script. How can i do that?

I tried to write a script but got no result

echo "first parameter is $1"
awk -F, 'NR>$1 && NR <10 {$8="abc";}1' OFS=, x.csv > y.csv

Upvotes: 0

Views: 134

Answers (2)

Tiago Lopo
Tiago Lopo

Reputation: 7959

Use -v option to pass variable:

Ex:

awk -F, -v start=1 'NR>start && NR < 10 ' /etc/passwd
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh

Another way to pass variable:

awk -F, 'NR>start && NR < 10 ' start=8 /etc/passwd
mail:x:8:8:mail:/var/mail:/bin/sh

And yet another way:

start=8; awk -F, 'NR>'$start' && NR < 10 ' /etc/passwd
mail:x:8:8:mail:/var/mail:/bin/sh

Upvotes: 1

P.P
P.P

Reputation: 121387

You can use -v to pass variables from your shell script:

start=$1
awk -F, -v start=1 'NR>start && NR <10 {$8="abc";}1' OFS=, x.csv > y.csv

Similarly, you can pass mulitple variables with:

awk -v start=1 -v end=10 ...

Upvotes: 0

Related Questions