perl 使用awk为每个字段插入引号

gdx19jrr  于 2022-11-15  发布在  Perl
关注(0)|答案(2)|浏览(140)

我正在寻找下面的输入基于下面提供的示例

样品:

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 sugest。
下面是命令:awk ′ {对于(i=1;示例

zhte4eai

zhte4eai1#

请尝试以下操作(仅使用提供的样品进行测试)。

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"

***说明:***现在添加上述代码的说明。

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.
ozxc1zmp

ozxc1zmp2#

在这里,您可以将FPATgnu awk配合使用

awk -v FPAT='([^~]*)|("[^"]+")' -v OFS="~" '{for (i=1;i<=NF;i++) if ($i!~/^\"/) $i="\""$i"\""} 1' file
"eno"~"ename"~"address"~"zip"
"123"~"abc"~""~"560000"
"245"~"abc ~ def"~"hyd"~"560102"
"333"~"ghi~jkl"~"pub"~"560103"

我们不告诉字段分隔符的样子,而是告诉字段的样子。然后测试字段是否没有双引号,如果没有,就添加它。
然后,您可以根据需要轻松更改字段分隔符:

awk -v FPAT='([^~]*)|("[^"]+")' -v OFS="," '{for (i=1;i<=NF;i++) if ($i!~/^\"/) $i="\""$i"\""} 1' file
"eno","ename","address","zip"
"123","abc","","560000"
"245","abc ~ def","hyd","560102"
"333","ghi~jkl","pub","560103"

相关问题