Cyndi Kaulitz
Cyndi Kaulitz

Reputation: 75

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.

Upvotes: 2

Views: 2233

Answers (3)

Cyndi Kaulitz
Cyndi Kaulitz

Reputation: 75

I tried

sed '/@PL/aline' 

and then

perl -pi -e 's[line\n][PREFIX]g' 

and it worked too. But your codes are easier, so I will use them.

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203502

Just use awk:

$ awk '{print (prev ~ /^@PL/ ? "PREFIX" : "") $0; prev=$0}' file
@PL123
PREFIXabcd
+
linewithmoretext
@PL456
PREFIXefgh
+
2ndlinewithmoretext

Upvotes: 2

oguz ismail
oguz ismail

Reputation: 50750

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

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

Upvotes: 3

Related Questions