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{
Asked
Active
Viewed 2,084 times
4

fep92
- 93
- 8
-
Preferably within a file but either in the file or STDOUT is fine. – fep92 Jul 25 '17 at 15:54
2 Answers
8
You can run
sed -i -e 's/}{/}\n{/g' filename.ext
where
sed
is your stream editor program-i
is the option to edit filefilename.ext
in place-e
means that a regular expression followss/}{/}\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 omitg
, 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

amphibient
- 29,770
- 54
- 146
- 240
-
-
1Best help ever. Used it for Amazon Access Logs in S3 from API Gateway. I added an extra `\n` so its easier to read and grep from there. Thank you! – Tony-Caffe Apr 06 '21 at 20:13
3
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.

yinnonsanders
- 1,831
- 11
- 28