使用awk为每个字段插入引号 [英] insert quotes for each field using awk
本文介绍了使用awk为每个字段插入引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在根据下面提供的示例寻找下面的输入
I am looking for below input based on the sample provided below
示例:
eno~ename~address~zip
123~abc~~560000~"a~b~c"
245~"abc ~ def"~hyd~560102
333~"ghi~jkl"~pub~560103
预期输出:
"eno"~"ename"~"address"~"zip"
"123"~"abc"~""~"560000"~"a~b~c"
"245"~"abc ~ def"~"hyd"~"560102"
"333"~"ghi~jkl"~"pub"~"560103"
我在awk中尝试过的
命令,如果定界符值包含在数据中,它将不起作用.如果还有其他建议,请加上perl/sed/awk建议.
command which i tried in awk it doesn't work if the delimiter value contains in data. If there are any alternate suggestions with perl/sed/awk suggest.
下面是命令:awk'{for(i = 1; i< = NF; i ++)$ i ="\""$ i" \"} 1'FS =〜" OFS =〜"样本
Below is the command : awk '{for (i=1;i<=NF;i++) $i="\""$i"\""}1' FS="~" OFS="~" sample
推荐答案
能否请您尝试以下操作(仅通过提供的示例进行测试).
Could you please try following(tested with provided samples only).
awk 'BEGIN{s1="\"";FS=OFS="~"} {for(i=1;i<=NF;i++){if($i!~/^\"|\"$/){$i=s1 $i s1}}} 1' Input_file
输出如下.
"eno"~"ename"~"address"~"zip"
"123"~"abc"~""~"560000"
"245"~"abc ~ def"~"hyd"~"560102"
"333"~"ghi~jkl"~"pub"~"560103"
说明: 现在为上述代码添加说明.
Explanation: Adding explanation for above code now.
awk ' ##Starting awk program here.
BEGIN{ ##Starting BEGIN section of awk program here.
s1="\"" ##Setting variable s1 to " here.
FS=OFS="~" ##Setting value of FS and OFS as ~ here.
} ##Closing BEGIN block of awk code here.
{
for(i=1;i<=NF;i++){ ##Starting for loop here from i=1 to till value of NF here.
if($i!~/^\"|\"$/){ ##Checking condition of value of current field is NOT having s1 value in it.
$i=s1 $i s1 ##Adding s1 variable before and after the value of $i.
} ##Closing block for if condition.
} ##Closing block for for loop here.
} ##Closing main block here.
1 ##Mentioning 1 will print the lines of Input_file.
' Input_file ##mentioning Input_file name here.
这篇关于使用awk为每个字段插入引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文