2

I need to split lines and print it to next line when pattern match.

Like I have:

ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955 

And I want it to print to new line when ABC pattern will come:

ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955 

5 Answers 5

2
sed -E -e 's/ (ABC)/\n\1/g' 

The sed command replaces any instance of ABC with a newline followed by ABC. It uses the () to capture part of the match (ABC without the leading space) and \1 to include it in the replacement.

e.g.

$ echo 'ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955'| sed -E -e 's/ (ABC)/\n\1/g' ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955 
1

With sed:

$ sed -e 's/ ABC/\ ABC/g' <file ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955 
0

Try this awk.

echo "ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955" | awk '{for(i=1;i<=NF;i++) if(match($i,"ABC")>0) line=line "\n"$i;else line=line $i; sub("^\n","",line); print line}' 

Creates a line with all fields, adding in front of the fields that begin with "ABC" a line break. Finally it eliminates the first line break and prints

0

You can also do it with paste and tr:

$ echo 'ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955' | tr ' ' '\n' | paste -d ' ' - - ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955 
0

Using Perl

~$ printf "ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955\n" | perl -pe 's/\h+ABC/\ ABC/g' ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955 

Above Perl answer is most similar to the excellent sed answer posted by @cuonglm. In Perl-family languages, the -pe commandline flags give sed-like behavior, i.e. execution, linewise-with-autoprinting. the \h+ atom stands for horizontal whitespace.


Using Raku (formerly known as Perl_6)

~$ printf "ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955\n" | raku -pe 's:g/ \h+ ABC/{"\n"}ABC/' ABC123xxx:: 2345 ABC345yyy:: 5678 ABC986zzz:: 7955 

The above Raku answer (formerly Perl6) is almost identical the Perl(5) answer. However to use the :global modifier, it gets moved to the head of the s:g/// idiom. Also, if you want run code within the replacement-half [ example {"\n"} ], simply enclose it in curlie braces, which helps with readability--very easy to see a \n newline is being inserted.


Perl References:
https://perldoc.perl.org
https://www.perl.org

Raku References:
https://docs.raku.org
https://raku.org

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.