Question:

How to add hostname as first line of a file

Kayden: 02 February 2022

I have a file which has a few lines.

one
two
three
four
five

I need to add hostname of the server I'm working on as the first line of the file. For example if abcd555.india.com is the server, the output file should be like :

abcd555.india.com
one
two
three
four
five

Hope my question is clear! I would be grateful to anyone who helps me out in this hour of need.

Answer:
Ruby: 02 February 2022

Use the vi command

:0r !hostname

Or, in its longer form,

:0read !hostname

You would have to press Esc first, of course.

The read command usually takes a filename and inserts the contents of that file beneath the current line, but if you specify a shell command with ! in front of it, it will take the output from that command and insert that beneath the current line.

However, we don't just want to insert this anywhere. We want to insert it on the first line. That's why we say 0r. The zero specifies the line number after which the command output (or file) will be placed.