wizurd
wizurd

Reputation: 3739

Replace newlines for lines matching regular expression

I have a file like:

72810 82:28:1
this is text
hello world

72810 82:28:12
some more text
hello wolrd again

I need to replace the newline characters in just the lines containing 72810* But there's a catch: I have tried the following:

sed 's/\n/ /g' myfile.txt

But this doesn't work.

I have also tried:

cat myfile.txt | perl -p -e 's/72810.*\n/72810 /g'

But this doesn't save the full original text (72810 82:28:1 or 72810 82:28:12 in this case).

What do I need to do to end up with the file looking like:

72810 82:28:1 this is text
hello world

72810 82:28:12 some more text
hello world again

By the way, I'm using solaris.

Upvotes: 0

Views: 55

Answers (3)

potong
potong

Reputation: 58391

This might work for you (GNU sed):

sed '/^72810/{N;s/\n/ /}' file

Upvotes: 0

Borodin
Borodin

Reputation: 126722

It seems simplest just to substitute the newline on all the lines that contain the test string. Like this

perl -pe "s/\n/ / if /72810/" myfile.txt

output

72810 82:28:1 this is text
hello world

72810 82:28:12 some more text
hello wolrd again

Upvotes: 2

Lee Duhem
Lee Duhem

Reputation: 15121

Try this:

perl -ne 'if (m/72810/) {s/\n/ /; print} else { print }' input.txt

Or this even shorter version:

perl -pe 's/\n/ / if m/72810/' input.txt

You can use -i option to edit that input.txt in place.

Upvotes: 2

Related Questions