Sed返回引用

时间:2017-09-27 22:58:37

标签: sed backreference

我有一个文本文件mountainList.txt,里面有以下内容:

      Brasstown Bald, (summit),4784,feet,Union County
Rabun Bald, (summit),4696,feet,Rabun County
Dick's Knob, (summit),4620,feet,Rabun County
              Hightower Bald, (summit),4568,feet,Towns County
Wolfpen Ridge, (ridge high point),4561,feet,Towns and Union Counties 
     Blood Mountain, (summit),4458,feet,Union County
Tray Mountain, (summit), 4430,feet,Towns County
          Grassy Ridge, (ridge high point),4420,feet,Rabun County
Slaughter Mountain, (summit),4338,feet,Union County
Double Spring Knob, (summit),4280,feet,Rabun County
Coosa Bald, (summit),4280,feet,Union County

我试图支持参考,以获得山名和县(即Brasstown Bald,Union County)。我有一个表达,但它没有正常工作:

sed -E 's/(.+, )(.+),(\w+ Count[yies]+)/\1\3/' mountainList.txt

它做我想要的,但仅限于第一行。有人可以解释为什么会这样吗?

3 个答案:

答案 0 :(得分:0)

使用您的命令,似乎可以正常工作

$ sed -E 's/(.+, )(.+),(\w+ Count[yies]+)/\1\3/' mountainList.txt
      Brasstown Bald, Union County
Rabun Bald, Rabun County
Dick's Knob, Rabun County
              Hightower Bald, Towns County
Wolfpen Ridge, (ridge high point),4561,feet,Towns and Union Counties 
     Blood Mountain, Union County
Tray Mountain, (summit), Towns County
          Grassy Ridge, Rabun County
Slaughter Mountain, Union County
Double Spring Knob, Rabun County
Coosa Bald, Union County

我正在使用这个版本的sed:

$ sed --version
sed (GNU sed) 4.4

答案 1 :(得分:0)

这可能适合你(GNU sed):

sed -r 's/^\s*([^,]*),.*,.*,.*,(.*)\s*$/\1, \2/' file

使用,分隔符捕获第一个和最后一个字段。

答案 2 :(得分:0)

数据是结构化的,因此 awk 解决方案也适用:

$ awk -F, '{ sub(/^ */,"",$1); print $1,"-", $5 }' input.txt
Brasstown Bald - Union County
Rabun Bald - Rabun County
Dick's Knob - Rabun County
Hightower Bald - Towns County
Wolfpen Ridge - Towns and Union Counties
Blood Mountain - Union County
Tray Mountain - Towns County
Grassy Ridge - Rabun County
Slaughter Mountain - Union County
Double Spring Knob - Rabun County
Coosa Bald - Union County