Shahin
Shahin

Reputation: 1316

bash command to remove new lines if condition on the next line is met

I have the following file

cat file.txt

Alex
Josh
c.ab23
Shawn
c.a13
c.oq42
Allie
c.ba212

I would like to replace the new lines with a tab only if the next line starts with c. as follows:

Alex
Josh    c.ab23
Shawn   c.a13   c.oq42
Allie   c.ba212

I thought something similar to

perl -pe 's/\nc\./\t/g'

Though I guess perl reads line by line. Is there another simple command that would do this?

Upvotes: 0

Views: 77

Answers (2)

Grinnz
Grinnz

Reputation: 9231

Your perl command can operate on the whole text at once with the -0777 switch:

perl -0777 -pe 's/\n(?=c\.)/\t/g' file.txt

(and in-place, if you add the -i switch)

Upvotes: 3

TheMadsen
TheMadsen

Reputation: 303

awk '/^c\./ {P=P"\t"$0; next} {if (P) print P; P=$0} END {if (P) print P}' < file.txt

Outputs

Alex
Josh    c.ab23
Shawn   c.a13   c.oq42
Allie   c.ba212

Upvotes: 1

Related Questions