How to add a new text line at the first line of a file?

File:

TABLE1

1234 
9555    
87676  
2344

Expected output:

Description of the following table:
TABLE1

1234
9555
87676
2344

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Actually echo and cat are enough to do what you want :

echo "Description of the following table:" | cat - file

The - argument tells cat to read from stdin.

Method 2

With sed:

$ sed -e '1i
Description of the following table:
' <file
Description of the following table:
TABLE1

1234
9555
87676
2344

Method 3

printf "%sn" 1 i "Description of the following table:" . w | ed filename

The printf outputs ed commands (one per line) which are then piped into ed filename.

ed edits the file as instructed:

1                                        # go to line 1
i                                        # enter insert mode
Description of the following table:      # text to insert
.                                        # end insert mode
w                                        # write file to disk

BTW, ed performs a real in-place edit, not write-to-temp-file-and-move like sed and most other text editing tools. The edited file keeps the same inode in the filesystem.

Method 4

The awk option would be :

gawk '
      BEGIN{print "Description of the following table:"}
      {print $0}' file > temp && mv temp file

A bit more work than sed here because sed has got an in-place edit option -i by which you could directly write to file.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x