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?
上面的命令将x.csv文件的第8列替换为字符串abc,行号为1到10成功。但我想在shell脚本中使用命令行参数传递起始行号(即1)。我怎样才能做到这一点?
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
2 个解决方案
#1
0
You can use -v
to pass variables from your shell script:
您可以使用-v从shell脚本传递变量:
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 ...
#2
1
Use -v
option to pass variable:
使用-v选项传递变量:
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
#1
0
You can use -v
to pass variables from your shell script:
您可以使用-v从shell脚本传递变量:
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 ...
#2
1
Use -v
option to pass variable:
使用-v选项传递变量:
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