简体   繁体   English

使用awk或sed添加空白列

[英]Add blank column using awk or sed

I have a file with the following structure (comma delimited) 我有一个具有以下结构的文件(以逗号分隔)

116,1,89458180,17,FFFF,0403254F98

I want to add a blank column on the 4th field such that it becomes 我想在第四个字段上添加一个空白列,使其变为

116,1,89458180,,17,FFFF,0403254F98

Any inputs as to how to do this using awk or sed if possible ? 是否有可能使用awk或sed进行任何输入?

thank you 谢谢

Assuming that none of the fields contain embedded commas, you can restate the task as replacing the third comma with two commas. 假设所有字段都不包含嵌入式逗号,则可以将任务重新声明为用两个逗号替换第三个逗号。 This is just: 这只是:

sed 's/,/,,/3'

With the example line from the file: 与文件中的示例行:

$ echo "116,1,89458180,17,FFFF,0403254F98" | sed 's/,/,,/3'
116,1,89458180,,17,FFFF,0403254F98

You can use this awk , 您可以使用此awk

awk -F, '$4="," $4' OFS=, yourfile

(OR) (要么)

awk -F, '$4=FS$4' OFS=, yourfile

If you want to add 6th and 8th field, 如果要添加第六和第八字段,

awk -F, '{$4=FS$4; $1=FS$1; $6=FS$6}1' OFS=, yourfile

Through awk 通过awk

$ echo '116,1,89458180,17,FFFF,0403254F98' | awk -F, -v OFS="," '{print $1,$2,$3,","$4,$5,$6}'
116,1,89458180,,17,FFFF,0403254F98
  • It prints a , after third field(delimited) by , 它打印,之后第三字段由(分隔) ,

Through GNU sed 通过GNU sed

$ echo 116,1,89458180,17,FFFF,0403254F98| sed -r 's/^([^,]*,[^,]*,[^,]*)(.*)$/\1,\2/'
116,1,89458180,,17,FFFF,0403254F98
  • It captures all the characters upto the third command and stored it into a group. 它捕获直到第三个命令的所有字符,并将其存储到一个组中。 Characters including the third , upto the last are stored into another group. 字符,包括第三,高达最后被存储到另一组。 In the replacement part, we just add an , between these two captured groups. 在更换零件,我们只需要加一个,这两个拍摄组之间。 Through Basic sed, 通过Basic sed,

Through Basic sed 通过基本sed

$ echo 116,1,89458180,17,FFFF,0403254F98| sed 's/^\([^,]*,[^,]*,[^,]*\)\(.*\)$/\1,\2/'
116,1,89458180,,17,FFFF,0403254F98

echo 116,1,89458180,17,FFFF,0403254F98|awk -F',' '{print $1","$2","$3",,"$4","$5","$6}'

Non-awk 非awk

t="116,1,89458180,17,FFFF,0403254F98"
echo $(echo $t|cut -d, -f1-3),,$(echo $t|cut -d, -f4-)

You can use bellow awk command to achieve that.Replace the $3 with what ever the column that you want to make it blank. 您可以使用bellow awk命令来实现这一点,将$ 3替换为您想使其空白的任何列。

awk -F, '{$3="" FS $3;}1' OFS=, filename awk -F,'{$ 3 =“” FS $ 3;} 1'OFS =,文件名

sed -e 's/\([^,]*,\)\{4\}/&,/' YourFile

自行替换4 [内容(非逗号),而不是逗号)的序列,然后用逗号替换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM