用awk或sed替换模式

时间:2016-11-09 08:47:40

标签: bash awk sed

我有一个包含以下图案的文件

*IFile

这里我需要替换所有12345343|559|-2,0,-200000,-20|20161108000000|FL|62,859,1439,1956|0,0,21300,0|S 3434344|-100000|20161108000000|GL|135|0|S 45454545|214|-2000,-2,0,0,-20|20161108000001||21,62,859,969,1956|77440,0,0,0,0|S 值并获取子集

中的第一个值

必需的输出:

,

我尝试了12345343|559|-2|20161108000000|FL|62|0|S 3434344|-100000|20161108000000|GL|135|0|S 45454545|214|-200000|20161108000001||21|77440|S 但没有工作

2 个答案:

答案 0 :(得分:4)

好的,最简单的:

$ sed 's/,[^|]*//g' ip.txt 
12345343|559|-2|20161108000000|FL|62|0|S
3434344|-100000|20161108000000|GL|135|0|S
45454545|214|-2000|20161108000001||21|77440|S

只需替换,后跟非|个字符,无需


perl

相同
$ perl -pe 's/,[^|]*//g' ip.txt 
12345343|559|-2|20161108000000|FL|62|0|S
3434344|-100000|20161108000000|GL|135|0|S
45454545|214|-2000|20161108000001||21|77440|S


使用awk,礼貌@JamesBrown

$ awk '{gsub(/,[^|]*/,"")} 1' ip.txt 
12345343|559|-2|20161108000000|FL|62|0|S
3434344|-100000|20161108000000|GL|135|0|S
45454545|214|-2000|20161108000001||21|77440|S

$ awk 'gsub(/,[^|]*/,"")+1' ip.txt 
12345343|559|-2|20161108000000|FL|62|0|S
3434344|-100000|20161108000000|GL|135|0|S
45454545|214|-2000|20161108000001||21|77440|S

答案 1 :(得分:2)

这是完成任务的一种方法:

awk 'BEGIN{FS=OFS="|"} {i=0; while(++i<=NF) gsub(/,.*/,"",$i)}1' File

输出:

12345343|559|-2|20161108000000|FL|62|0|S
3434344|-100000|20161108000000|GL|135|0|S
45454545|214|-2000|20161108000001||21|77440|S