Pattern conversion in Unix

Viewed 82

I am new to the shell script, I have a text file with multiple records, and the 1st record end and second record start in the same line as below

"-}{"

So I want to break the chain as

"-} #line1

{ #line2"

I tried like below: Method 1

sed 's/\-\}\{//\-\} \n \{' file.txt

Method 2

tr '-}{' '\n'

Can anyone please help me with this?

4 Answers

Too much escaping.

Also it's s/<pattern>/<replacement>/. There are 3 /, the last one on the end.

$ echo '"-}{"' | sed 's/-}{/-} \n {/'
"-} 
 {"

It's not possible to with tr, tr is for single character translate. If you would like tr -- '-}{' '\n' then tr would replace any of -, } and { by a newline.

With your shown samples, please try following awk code. Simply substituting -}{ with -} new line { and printing the value.

echo '"-}{"' | awk '{sub(/-}{/,"-}\n{")} 1'

This might work for you (GNU sed):

sed 'G;:a;s/-}\({.*\(.\)\)/-}\2\1/;ta;s/.$//' file

Append a newline to the current line.

Use pattern matching to insert the newline between -} and { repeatedly.

When all is done, remove the introduced newline.

You can use () to capture the delimiters and do this:

echo '"-}{" -}       -}{' | sed -E 's/(-})({)/\1\n\2/g'
"-}
{" -}       -}
{
Related