Hamad
Hamad

Reputation: 23

How to split a line on every match reading from file

A kind of new learner of linux and need your bit of help here. This code

sed 's/regexp/&\n/g' file.txt

works only on first match gives the output on first match only and then it stops reading the rest of line.

What if I want to keep on reading the line till end and move the line to new line on every match?

For example I have a log file like the following

some text here Critical and some text here Critical and again some text here Critical.

I want to break it like the following

some text here
Critical and some text here
Critical and again some text here

Upvotes: 2

Views: 105

Answers (2)

atanation
atanation

Reputation: 66

You can try this Perl one-liner:

cat file.txt | perl -ne 'chomp; @y = split(/Critical/, $_); print join("\nCritical", @y) . "\n"'

This assumes the contents of file.txt is just one long line like this as you indicated:

some text here Critical and some text here Critical and again some text here

output:

some text here 
Critical and some text here 
Critical and again some text here

Upvotes: 1

khrm
khrm

Reputation: 5753

You have to use g for changing globally.

echo "some text here Critical and some text here Critical and again some text here Critical." | sed -e 's:Critical:\nCritical:g'

Eventhough this will work, I would recommend you to use this:

echo "some text here Critical and some text here Critical and again some text here Critical." | sed -e 's:Critical:\
> Critical:g'

Where > is prompt character. You don't have to use it. You will get it. This is the portable way to use sed to change new lines. All other ways aren't portable.

To read from file:

sed -e 's:Critical:\
Critical:g' file

Upvotes: 1

Related Questions