问题
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