How to append text to the end of a certain line of a file?

If I needed to append a username to the end line 32 on a file, how would I do so?

I can find on Google how to add text to the beginning of a line with sed, but I can’t figure out how I would append it to the end, or even the middle, if that was possible.

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

You can substitute your text for the line end ($) like this:

sed -e '32s/$/your_text/' file

To insert text in the middle of the line some information about the line structure would be useful.

Method 2

Try:

sed  '32s,$,SOMETHING TO ADD,' FILE

Method 3

Using awk:

awk -v username='some username' -v line=32 'NR == line { $0 = $0 username } 1' file

To insert the username into the middle of the line, one would have to know more about what the lines in the file looks like.

If the username and line are variables:

awk -v username="$username" -v line="$line" 'NR == line { $0 = $0 username } 1' file

If you want to insert a space before the username:

awk -v username="$username" -v line="$line" 'NR == line { $0 = $0 " " username } 1' file

Method 4

Using ed:

$ seq 100 > 100file
$ username=jeff
$ ed -s 100file <<< $'32s/$/'"$username"$'/nwnq'
$ sed -n 28,34p 100file
28
29
30
31
32jeff
33
34

The trailing / of the replacement string suppresses the default-print behavior.


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