4

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.

1
  • By “the middle” do you mean the exact center of the line (with an even length)? Or just some position between the beginning and the end? In this case, how do you determine it?
    – Renardo
    Jun 19, 2018 at 15:41

4 Answers 4

10

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.

3

Try:

sed  '32s,$,SOMETHING TO ADD,' FILE
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
0

Using ed:

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .