4

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.

Sundeep
  • 23,246
  • 2
  • 28
  • 103
gosatriani
  • 307
  • 4
  • 11

2 Answers2

4

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:"")}'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • Sorry what i meant was to append to the next line after AIX – gosatriani Dec 28 '17 at 06:33
  • @gosatriani, changed the code now, please check and let me know if this helps you. – RavinderSingh13 Dec 28 '17 at 06:39
  • 1
    Good portable solution not limited to sed version! (e.g. works also on mac) – al-ash Nov 17 '20 at 20:27
  • @al-ash, your welcome cheers and happy learning – RavinderSingh13 Nov 17 '20 at 20:37
  • 1
    Thx! Actually, I just realized that your awk script is not matching a line with "AIX" pattern but line which is identical "AIX". Per the title of this thread, it might be useful to append to your answer that "~" instead of "==" comparator could be used here. – al-ash Nov 17 '20 at 20:50
  • 1
    @al-ash, since answer is old one I am not editing it right now, as per your suggestion I am adding it here for future user's reference `awk -v host=$(hostname) '{printf("%s%s\n",$0,$0~/^AIX$/?RS host:"")}'` cheers. – RavinderSingh13 Nov 17 '20 at 20:52
2

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
SLePort
  • 15,211
  • 3
  • 34
  • 44