..

Insert a new line before a pattern match using awk

One day, working on a project in WorldServer, I’ve downloaded a target file that somehow got truncated after the project was finished. The source file used to create the project was a .strings file. The target file, instead of having “key = value” on each line, had everything in one single line.

I started looking for solutions and found that you can use the awk’s variable assignment feature (-v switch) to assign a variable’s value - in this example, pattern=”foo.bar” - before using dynamic regexps to match the given pattern.

When awk finds the pattern, it appends a new line before it.

awk -v pattern="foo.bar" '$0 ~ pattern {gsub(pattern, "\n"pattern)}1' filename

Before:

foo.bar.text1=nononononononofoo.bar.text2=nononononononono

After:

foo.bar.text1=nonononononono
foo.bar.text2=nononononononono

Note: This example works fine because all keys have the same prefix, “foo.bar.”, your mileage may vary.

awk(1) Mac OS X Manual Page