Awk adding constant values

时间秒杀一切 提交于 2019-12-13 05:17:22

问题


I have data in the text file like val1,val2 with multiple lines and I want to change it to 1,val1,val2,0,0,1

I tried with print statement in awk(solaris) to add constants by it didn't work.

What is the correct way to do it ?


(From the comments) This is what I tried

awk -F, '{print "%s","1,"$1","$2"0,0,1"}' test.txt 

回答1:


Based on the command you posted, a little change makes it:

$ awk -F, 'BEGIN{OFS=FS} {print 1,$1,$2,0,0,1}' file
1,val1,val2,0,0,1

OR using printf (I prefer print):

$ awk -F, '{printf "1,%s,%s,0,0,1", $1, $2}' file
1,val1,val2,0,0,1



回答2:


To prepend every line with the constant 1 and append with 0,0,1 simply do:

$ awk '{print 1,$0,0,0,1}' OFS=, file
1,val1,val2,0,0,1

A idiomatic way would be:

$ awk '$0="1,"$0",0,0,1"' file
1,val1,val2,0,0,1



回答3:


Using sed:

sed 's/.*/1,&,0,0,1/' inputfile

Example:

$ echo val1,val2 | sed 's/.*/1,&,0,0,1/'
1,val1,val2,0,0,1


来源:https://stackoverflow.com/questions/19097255/awk-adding-constant-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!