bash script append text to first line of a file bash script append text to first line of a file linux linux

bash script append text to first line of a file


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


This is a solution to add "ok" at the first line on /etc/passwd, I think you can use this in your script with a little bit of 'tuning' :

$ awk 'NR==1{printf "%s %s\n", $0, "ok"}' /etc/passwdroot:x:0:0:root:/root:/bin/bash ok


To edit a file, you can use ed, the standard editor:

line=' bcm2708.w1_gpio_pin=20'file=/boot/cmdline.txtif ! grep -q -x -F -e "$line" <"$file"; then    ed -s "$file" < <(printf '%s\n' 1 a "$line" . 1,2j w q)fi

ed's commands:

  • 1: go to line 1
  • a: append (this will insert after the current line)
  • We're in insert mode and we're inserting the expansion of $line
  • .: stop insert mode
  • 1,2j join lines 1 and 2
  • w: write
  • q: quit