0
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
1
  • awk reads the input line by line. so it starts from first line only. Commented Jun 24, 2014 at 9:51

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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 ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.