bash script append text to first line of a file

Ryu Kajiya picture Ryu Kajiya · Nov 16, 2014 · Viewed 13.2k times · Source

I want to add a text to the end of the first line of a file using a bash script. The file is /etc/cmdline.txt which does not allow line breaks and needs new commands seperated by a blank, so text i want to add realy needs to be in first line.

What i got so far is:

line=' bcm2708.w1_gpio_pin=20'
file=/boot/cmdline.txt
if ! grep -q -x -F -e "$line" <"$file"; then
  printf '%s' "$line\n" >>"$file"
fi

But that appends the text after the line break of the first line, so the result is wrong. I either need to trim the file contend, add my text and a line feed or somehow just add it to first line of file not touching the rest somehow, but my knowledge of bash scripts is not good enough to find a solution here, and all the examples i find online add beginning/end of every line in a file, not just the first line.

Answer

Skynet picture Skynet · Nov 16, 2014

This sed command will add 123 to end of first line of your file.

sed ' 1 s/.*/&123/' yourfile.txt

also

sed '1 s/$/ 123/' yourfile.txt

For appending result to the same file you have to use -i switch :

sed -i ' 1 s/.*/&123/' yourfile.txt