Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add line after matching a pattern [duplicate]

Tags:

bash

echo

sed

awk

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.

like image 283
gosatriani Avatar asked Oct 18 '25 03:10

gosatriani


1 Answers

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:"")}'
like image 158
RavinderSingh13 Avatar answered Oct 21 '25 01:10

RavinderSingh13