Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

replace columns UNIX with awk

I want to replace data in spcific column that the user gives with id, with a value that again is given by the user. So the user gives the id of the row, the column, and the value to replace in the column.

i have this code :

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

but when i run it like this

./tool.sh Yang POUTSES

it gives nothing

persons.dat.txt :

933|Mahinda|Perera|male|1989-12-03|2010-03-17T13:32:10.447+0000|192.248.2.123|Firefox
1129|Carmen|Lepland|female|1984-02-18|2010-02-28T04:39:58.781+0000|81.25.252.111|Internet Explorer
4194|Há?“ Ch?-|Do|male|1988-10-14|2010-03-17T22:46:17.657+0000|103.10.89.118|Internet Explorer
8333|Chen|Wang|female|1980-02-02|2010-03-15T10:21:43.365+0000|1.4.16.148|Internet Explorer
8698|Chen|Liu|female|1982-05-29|2010-02-21T08:44:41.479+0000|14.103.81.196|Firefox
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You code does not match your requirement at all:

the user gives the id of the row, the column, and the value to replace

which I would interpret with

awk -v row=2 -v col=3 -v new_value="Hello World" '
    BEGIN { FS = OFS = "|" }
    NR == row {$col = new_value}
    {print}
' persons.dat.txt

Note the use of variables here:

  • an unadorned variable is like C, replace with the variable's value (usage of the "row" variable
  • the $ symbol is like an operator that references the value of the field number given by the value (here, "$col")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...