Add line after matching a pattern [duplicate]

元气小坏坏 提交于 2021-01-27 14:09:48

问题


I have a file say test with following values

Linux
Solaris
Fedora
Ubuntu
AIX
HPUX

How to add a line with system hostname after the line matching AIX? If I do

echo `hostname` >> test

system hostname comes at the last after HPUX.


回答1:


With sed:

sed "s/^AIX$/& $(hostname)/" file

If the line could contain AIX:

sed "s/AIX.*/& $(hostname)/" file

Edit:

To append the hostname after the matching line, try the a(append) command:

sed "/^AIX$/a $(hostname)" file



回答2:


Could you please try following awk and let me know if this helps you.

 awk -v host=$(hostname) '$0 == "AIX"{print $0 RS host;next} 1'  Input_file

EDIT: Adding 1 more solution too here.

awk -v host=$(hostname) '{printf("%s%s\n",$0,$0=="AIX"?RS host:"")}'


来源:https://stackoverflow.com/questions/48002485/add-line-after-matching-a-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!