Borys Bradel's Blog
How to add new lines to existing files
Tags: scripting April 12, 2009
I recently had to add new lines to existing files after certain characters, { and ;. The easiest is to use vim or sed. In both, a search and replace regular expression is used, which consists of a s/input pattern/output pattern/g, where the input pattern indicates what needs to be matched and the output pattern indicates what is to be the replacement (the s is for search and g is for global).
The trick in vim is to input a new line, which is represented by ^M. The way to achieve that is by the sequence ctrl-V ENTER or ctrl-V ctrl-M.
Then to add a new line after a single {, the command is :s/{ /{^M/
The following two commands will perform the command everywhere (the % is for all the lines and the g at the end is for all elements inside of a line):
:%s/{ /{^M/g
:%s/; /;^M/g
The trick in sed is to use a new line and to be in bash (sh and csh do not work). The two line sed script is:
sed 's/\([;{]\) /\1\
/g' filename
The \1 inserts whatever was found within the first \( \) of the first entry in the search regular expression. The last \ must be the last character in the line.
All the details need to be followed for the replacement to occur. The sed one is nice because it can be done at the command line.
Copyright © 2009 Borys Bradel. All rights reserved. This post is only my possibly incorrect opinion.