How to Add Text at the Beginning of Specific Lines Using Sed

How to add text at the beginning of specific lines using sed?

Whenever @PL is found, read next line and prepend PREFIX to it.

sed '/@PL/{n;s/^/PREFIX/}' file

Using sed to insert text at the beginning of each line

sed 's/^/rm -rf /' filename

EDIT

Xargs would be simpler way to delete all of the files listed in another file

xargs -a filename rm -rf

linux add string to beginning of specific lines

You need to capture and then reference the character matched by [^#]:

sed 's/^[^#]/text&/' infile > outfile

Add text to specific lines of a file using sed

this should do what you want:

sed '2,3{s/$/ 0 0 0/}' file

For details pls read the manpage/infopage of sed, the "address" section.

Using sed to add text after a pattern, but the added text comes from a list file

This is a bash script that uses sed and reads File_2 (The file containing the replacements) line by line, thus reading one replacement at a time. I then replaced the lines in File_1 with a sed script.

while IFS= read -r line; do
sed -i "0,/\/stash\/scm\/'/{s|/stash/scm/'|/stash/scm/${line}'|}" File_1.txt
done < File_2.txt

Some tricks used to do this:

  1. sed '0,/Apple/{s/Apple/Banana/}' input_filename Replace only the first occurrence in filename of the string Apple with the string Banana
  2. Using double quotes for the sed script to allow for variable expansion ${line}
  3. Making sure the search string to replace was being changed each iteration. This was done by including the ending single quote char ' for the search argument in the sed script s|/stash/scm/'|
  4. Reading a file line by line in a bash script
while IFS= read -r line; do
echo $line
done < File_2.txt

Read File line by line in bash

How do I insert text to the 1st line of a file using sed?

Suppose you have a file like this:

one
two

Then to append to the first line:

$ sed '1 s_$_/etc/example/live/example.com/fullchain.pem;_' file
one/etc/example/live/example.com/fullchain.pem;
two

To insert before the first line:

$ sed '1 i /etc/example/live/example.com/fullchain.pem;' file
/etc/example/live/example.com/fullchain.pem;
one
two

Or, to append after the first line:

$ sed '1 a /etc/example/live/example.com/fullchain.pem;' file
one
/etc/example/live/example.com/fullchain.pem;
two

Note the number 1 in those sed expressions - that's called the address in sed terminology. It tells you on which line the command that follows is to operate.

If your file doesn't contain the line you're addressing, the sed command won't get executed. That's why you can't insert/append on line 1, if your file is empty.

Instead of using stream editor, to append (to empty files), just use a shell redirection >>:

echo "content" >> file


Related Topics



Leave a reply



Submit