我有一个文件,我试图找出如何使用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
答案 0 :(得分:1)
请您尝试以下。
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.
答案 1 :(得分:0)
这可能对您有用(GNU sed):
sed '/^state/h;/city/!d;G;s/ *\nstate /,/;s/ *$//' file
将以state
开头的任何行复制到保留空间(HS)。删除任何不包含单词city的行。将HS附加到图案空间(PS)。删除当前行末尾的任何空格,附加的换行符和文字state
,后跟一个空格。删除行尾的所有其他空格。