Bash script add text to the first line of the file

I want to add text to the end of the first line of a file using a bash script. The file has a /etc/cmdline.txt file that does not allow line breaks and requires new commands separated by a space, so the text I want to add should really be on the first line.

What I got so far:

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 this adds the text after breaking the line of the first line, so the result is incorrect. I need to either trim the contend file, add text and a line feed, or somehow just add it to the first line of the file without touching the others somehow, but my knowledge of bash scripts is not good enough to find a solution here, and all the examples that I find on the Internet add the beginning / end of each line in the file, not just the first line.

+4
source share
3 answers

This command sedwill add 123to the end of the first line of your file.

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

and

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

To add the result to the same file, you must use the switch -i:

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

This solution is to add “ok” to the first line on /etc/passwd, I think you can use this in your script with a bit of “tweaking”:

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

, ed, :

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

ed :

  • 1: 1
  • a: append ( )
  • , $line
  • .:
  • 1,2j 1 2
  • w:
  • q:
0

All Articles