首页 > 解决方案 > 如何使用 sed 在两个模式之间添加线条?

问题描述

我有一个文件,我正在尝试弄清楚如何使用 sed 附加文本,如下所示;该文件包含与州有关的行,然后与该州的城市行。

state NY  
city Manhattan  
city Brooklyn  
city Bronx  
end state  
state CA  
city Los Angeles  
city San Francisco  
city San Diego  
end state  
state IL  
city Chicago  
city Springfield  
city Rockford  
end state  

试图以输出结束是标题信息(状态)被附加到城市行的末尾,所以我最终得到一个像这样的文件:

city Manhattan,NY  
city Brooklyn,NY  
city Bronx,NY  
city Los Angeles,CA  
city San Francisco,CA  
city San Diego,CA  
city Chicago,IL  
city Springfield,IL  
city Rockford,IL

标签: bashawksedappend

解决方案


请您尝试以下操作。

awk '/^state/{val=$NF;next} val{print $0","val}'  Input_file

说明:现在也添加说明。

awk '
/^state/{         ##Check condition if a line starts from string state then do following.
  val=$NF;        ##Creating variable val whose value is last field of current line.
  next}           ##Using next keyword to skip all further statements.
val{              ##Checking condition if variable val is NOT NULL then do following.
  print $0","val  ##Printing current line with command and variable val here.
}'  Input_file    ##Mentioning Input_file name here.

推荐阅读