根据字段数添加额外的字符串 - Sed/Awk [英] Add Extra Strings Based on count of fields- Sed/Awk
问题描述
我在文本文件中有以下格式的数据.
I have data in below format in a text file.
null,"ABC:MNO"
"hjgy","ABC:PQR"
"mn","qwe","ABC:WER"
"mn","qwe","mno","ABC:WER"
所有行都应该有 3 个字段,如第 3 行.我想要以下格式的数据.
All rows should have 3 fields like row 3. I want the data in below format.
"","","","ABC:MNO"
"hjgy","","","ABC:PQR"
"mn","qwe","","ABC:WER"
"mn","qwe","mno","ABC:WER"
如果该行以 null 开头,则应将 null 替换为 "","","",
If the row starts with null then null should be replace by "","","",
如果只有 2 个字段,则应在第一个字符串之后添加 "","",
.
If there are only 2 fields then "","",
should be added after 1st string .
如果有 3 个字段,则 "",
应该添加到第二个字符串之后
If there are 3 fields then "",
should be added after 2nd string
如果有 4 个字段,则什么都不做.
If there are 4 fields then do nothing.
我可以通过使用 sed 's/null/\"\",\"\",\"\"/' test.txt 来处理第一种情况
但我不知道如何处理接下来的两种情况.
But I dont know how to handle next 2 scenarios.
问候.
推荐答案
仅使用您显示的示例,请尝试以下操作.
With your shown samples only, please try following.
awk '
BEGIN{
FS=OFS=","
}
{
sub(/^null/,"\"\",\"\",\"\"")
}
NF==2{
$1=$1",\"\",\"\""
}
NF==3{
$2=$2",\"\""
}
1' Input_file
OR 将 "
作为变量,您也可以尝试以下操作:
OR make "
as a variable and one could try following too:
awk -v s1="\"\"" '
BEGIN{
FS=OFS=","
}
{
sub(/^null/,s1 "," s1","s1)
}
NF==2{
$1=$1"," s1 "," s1
}
NF==3{
$2=$2"," s1
}
1' Input_file
说明:为以上添加详细说明.
Explanation: Adding detailed explanation for above.
awk ' ##Starting awk program from here.
BEGIN{ ##Starting BEGIN section of this program from here.
FS=OFS="," ##Setting FS and OFS to comma here.
}
{
sub(/^null/,"\"\",\"\",\"\"") ##Substituting starting with space null to "","","", in current line.
}
NF==2{ ##If number of fields are 2 then do following.
$1=$1",\"\",\"\"" ##Adding ,"","" after 1st field value here.
}
NF==3{ ##If number of fields are 3 here then do following.
$2=$2",\"\"" ##Adding ,"" after 2nd field value here.
}
1 ##Printing current line here.
' Input_file ##Mentioning Input_file name here.
这篇关于根据字段数添加额外的字符串 - Sed/Awk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!