将用户变量放入SUB命令UNIX

时间:2016-03-31 08:43:25

标签: unix awk

我有这段代码:

awk -v antik1=$1 -v antik2=$2 '{ sub(/antik1/,"$antik2") ; print }' persons.dat.txt
echo " $1 , $2 "

我用这个命令给$ 1和$ 2:

./tool.sh  Yang replacement 

persons.dat.txt文件是:

> 16492674422392|Alberto|Parra|female|1985-09-22|2012-09-01T01:30:59.228+0000|190.96.12.239|Chrome
> 16492674424948|Peng|Chen|female|1984-07-26|2012-09-23T00:51:52.900+0000|1.4.10.198|Internet
> Explorer
> 16492674425075|Changpeng|Xu|female|1984-03-27|2012-10-02T03:55:00.946+0000|1.50.15.119|Firefox
> 16492674425398|Prince|Kobayashi|male|1989-08-07|2012-09-30T03:30:41.772+0000|14.101.89.18|Chrome
> 16492674426410|Yang|Wei|male|1980-07-01|2012-10-01T13:11:48.528+0000|27.144.204.193|Firefox

但是,当我执行时,它不会取代'杨'与'替换' 。所以,我的问题是,我怎样才能将变量$ 1和$ 2插入sub?有没有更好的方法呢?

2 个答案:

答案 0 :(得分:0)

删除第一行$ antik2前面的$,并删除更多控制字符

#!/bin/sh
awk -v antik1=$1 -v antik2=$2 '
    { r=$0; }   # set a default row value
antik1  { sub(antik1,antik2,r); }  # replace if antik1 matches
    { print r; } # print all lines.
END { print "replaced \""antik1"\" with \""antik2"\"."; } # print the arguments.
' person.txt

TEST OUTPUT

$ bash change_person.sh Y'.*'g test
16492674422392|Alberto|Parra|female|1985-09-22|2012-09-01T01:30:59.228+0000|190.96.12.239|Chrome
16492674424948|Peng|Chen|female|1984-07-26|2012-09-23T00:51:52.900+0000|1.4.10.198|Internet
Explorer
16492674425075|Changpeng|Xu|female|1984-03-27|2012-10-02T03:55:00.946+0000|1.50.15.119|Firefox
16492674425398|Prince|Kobayashi|male|1989-08-07|2012-09-30T03:30:41.772+0000|14.101.89.18|Chrome
16492674426410|test|Wei|male|1980-07-01|2012-10-01T13:11:48.528+0000|27.144.204.193|Firefox
replaced Y.*g with test.

答案 1 :(得分:0)

试试这个:

void*

运行命令:

git push

<强>输出:

awk -v antik1=$1 -v antik2=$2 '
{   
    sub(antik1, antik2);
    print;
}' persons.dat.txt