Ryu Kajiya
Ryu Kajiya

Reputation: 265

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.

Upvotes: 10

Views: 23683

Answers (4)

Joey Adams
Joey Adams

Reputation: 43380

This can be used to append a variable to the first line of input:

awk -v suffix="$suffix" '{print NR==1 ? $0 suffix : $0}'

This will work even if the variable could potentially contain regex formatting characters.

Example:

suffix=' [first line]'
cat input.txt | awk -v suffix="$suffix" '{print NR==1 ? $0 suffix : $0}' > output.txt

input.txt:

Line 1
Line 2
Line 3

output.txt:

Line 1 [first line]
Line 2
Line 3

Upvotes: 0

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

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

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'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

Upvotes: 2

Arnab Nandy
Arnab Nandy

Reputation: 6692

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

Upvotes: 25

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185025

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

Upvotes: 4

Related Questions