linuxsed

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


I want to add some text at the beginning of each line that is below a character. Using sed in the terminal.

For example. If I have a textA.txt

@PL123
abcd
+
linewithmoretext
@PL456
efgh
+
2ndlinewithmoretext

and so on, with many more lines following the same structure.

And I want my output to be: textB.txt

@PL123
PREFIXabcd
+
linewithmoretext
@PL456
PREFIXefgh
+
2ndlinewithmoretext

I have tried

sed 's/^/PREFIX/' textA.txt > textB.txt 

but that inserts PREFIX at the beginning of ALL lines. But I want it to be more specific, saying that I want PREFIX at the beginning of each line that is below the line containing @PL. Can anyone help me please? I'd be very thankful.


Solution

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

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