Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script append text to first line of a file

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.

like image 862
Ryu Kajiya Avatar asked Nov 16 '14 15:11

Ryu Kajiya


People also ask

How do I add text to the beginning of a file in bash?

You cannot insert content at the beginning of a file. The only thing you can do is either replace existing content or append bytes after the current end of file.

How do I append the first line of a file?

1 for first line, you can use num,num to assign range, eg 3,5 is change line 3 to line 5. s for substitute, $ means the end of the line. If you want change the file right away, use -i parameter, anyway, use it with caution.

How do you append the first line of a file in Unix?

Use sed 's insert ( i ) option which will insert the text in the preceding line.


2 Answers

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
like image 191
Skynet Avatar answered Nov 04 '22 00:11

Skynet


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/passwd
root:x:0:0:root:/root:/bin/bash ok
like image 30
Gilles Quenot Avatar answered Nov 03 '22 22:11

Gilles Quenot