如何在Unix中删除2个字符串之间的文本

时间:2017-06-09 15:39:46

标签: unix

使用UNIX命令,如何获得所需的输出,将邮政编码缩短到第一部分?

我已尝试sed命令,但无法使其正常工作。

输入:

"970000","SW3 2BZ","F","N","L","","LONDON"
"280000","SW5 9JZ","F","N","L","","LONDON"
"103000","CF35 3BG","S","N","F","RUMNEY"

期望输出:

"970000","SW3","F","N","L","","LONDON"
"280000","SW5","F","N","L","","LONDON"
"103000","CF35","S","N","F","RUMNEY"

4 个答案:

答案 0 :(得分:1)

使用

awk 'BEGIN{FS=OFS=","}{gsub(/ [^"]*/,"",$2)}1' file

<强>输入

$ cat file
"970000","SW3 2BZ","F","N","L","","LONDON"
"280000","SW5 9JZ","F","N","L","","LONDON"
"103000","CF35 3BG","S","N","F","RUMNEY"

<强>输出

$ awk 'BEGIN{FS=OFS=","}{gsub(/ [^"]*/,"",$2)}1' file
"970000","SW3","F","N","L","","LONDON"
"280000","SW5","F","N","L","","LONDON"
"103000","CF35","S","N","F","RUMNEY"

答案 1 :(得分:0)

EDIT 用sed:

sed 's/ [^"]*//'

答案 2 :(得分:0)

echo '"ABC","DEF EFG",123' | awk 'BEGIN{FS=",";OFS=","}{split($2,a,"   ");$2=a[1];print}'
"ABC","DEF,123

答案 3 :(得分:0)

awk '{sub(/ .{3]/,"")}1' file

"970000","SW3","F","N","L","","LONDON"
"280000","SW5","F","N","L","","LONDON"
"103000","CF35","S","N","F","RUMNEY"

删除空格和接下来的3个字符