Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a new line between 2 specific characters

Tags:

linux

bash

shell

Is there anyway to insert new lines in-between 2 specific sets of characters? I want to insert a new line every time }{ occurs in a text file, however I want this new line to be inserted between the 2 curly brackets. For example }\n{

like image 367
fep92 Avatar asked Dec 18 '22 05:12

fep92


2 Answers

You can run

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

where

  • sed is your stream editor program
  • -i is the option to edit file filename.ext in place
  • -e means that a regular expression follows
  • s/}{/}\n{/g is the regular expression meaning find all (g) instances of }{ in every line and replace them with }\n{ where \n is the regex for new line. If you omit g, it will only replace the first occurrence of the search pattern but still in every line.

To test before committing changes to your file, omit the -i option and it will print the result in STDOUT.

Example:

Create file:

echo "First }{ Last" > repltest.txt

Run

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

Prints the following to STDOUT:

First }
{ Last

To effect the change in the same file, use -i option.

To run this against STDIN instead of a file, omit -i and the filename in the piped command after something that outputs STDIN, for example:

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

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

like image 67
amphibient Avatar answered Dec 20 '22 19:12

amphibient


Use sed.

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

Every instance of }{ will be replaced with }\n{. You can use the -i flag if you want to replace the text in the file.

like image 44
yinnonsanders Avatar answered Dec 20 '22 19:12

yinnonsanders