3

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.

  • 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 '18 at 15:41
7

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.

4

Try:

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.