How to insert a new line between two specific characters

Is it possible to insert new lines between two specific character sets? I want to insert a new line every time it }{

happens in a text file, however I want this new line to be inserted between the two curly braces. for example}\n{

+3


source to share


2 answers


You can run

sed -i -e 's /} {/} \ n {/ g' filename.ext

Where

  • sed

    - your thread editor program
  • -i

    there is an option to edit the file filename.ext

    in place
  • -e

    means the regex follows
  • s/}{/}\n{/g

    is a regular expression meaning to find all ( g

    ) instances of } { in each line and replace them with } \ n { , where \n

    is a regular expression for a new line. If you omit it g

    , it only replaces the first occurrence of the search pattern, but still on every line.

To check before making changes to your file, omit the parameter -i

and it will print the result to STDOUT.

Example:

Create file:

echo "First }{ Last" > repltest.txt

      



Run

sed -e 's/}{/}\n{/g' repltest.txt

      

Outputs the following data to STDOUT:

First }
{ Last

      

To make a change in the same file, use the option -i

.

To run this instead of STDIN instead of file, omit -i

and the filename on the command line after whatever STDIN outputs, e.g .:

cat repltest.txt | sed -e 's/}{/}\n{/g'

      

which does the same as sed -e 's/}{/}\n{/g' repltest.txt

+7


source


Use sed

.

sed [-i] -e 's/}{/}\n{/g' file.txt

      



Each copy }{

will be replaced with }\n{

. You can use a flag -i

if you want to replace text in the file.

+3


source







All Articles