Insert linebreak in a file after a string

Viewed 80

I have a unique (to me) situation: I have a file - file.txt with the following data:

"Line1", "Line2", "Line3", "Line4"

I want to insert a linebreak each time the pattern ", is found. The output of file.txt shall look like:

"Line1", 
"Line2", 
"Line3", 
"Line4"

I am having a tough time trying to escape ", . I tried sed -i -e "s/\",/\n/g" file.txt, but I am not getting the desired result.

I am looking for a one liner using either perl or sed.

4 Answers

You may use this gnu sed:

sed -E 's/(",)[[:blank:]]*/\1\n/g' file.txt

"Line1",
"Line2",
"Line3",
"Line4"

Note how you can use single quote in sed command to avoid unnecessary escaping.

If you don't have gnu sed then here is a POSIX compliant sed solution:

sed -E 's/(",)[[:blank:]]*/\1\
/g' file.txt

To save changes inline use:

sed -i.bak -E 's/(",)[[:blank:]]*/\1\
/g' file.txt

Could you please try following. using awk's substitution mechanism here, in case you are ok with awk.

awk -v s1="\"" -v s2="," '{gsub(/",[[:blank:]]+"/,s1 s2 ORS s1)} 1' Input_file

Here's a Perl solution:

perl -pe 's/",\K/\n/g' file.txt

The substitution pattern matches the ",, but the \K says to ignore anything to the left for the replacement (so, ",) will not be replaced. The replacement then effectively inserts the newline.

I used the single quote for the argument to -e, but that doesn't work on Windows where you have to use ". Instead of escaping the ", you can specify it in another way. That's code number 0x22, so you can write:

perl -pe "s/\x22,\K/\n/g" file.txt

Or in octal:

perl -pe "s/\042,\K/\n/g" file.txt

Use this Perl one-liner:

perl -F'/"\K,\s*/' -lane 'print join ",\n", @F;' in_file > out_file

Or this for in-line replacement:

perl -i.bak -F'/"\K,\s*/' -lane 'print join ",\n", @F;' in_file

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-n : Loop over the input one line at a time, assigning it to $_ by default.
-l : Strip the input line separator ("\n" on *NIX by default) before executing the code in-line, and append it when printing.
-a : Split $_ into array @F on whitespace or on the regex specified in -F option.
-F'/"\K,\s*/' : Split into @F on a double quote, followed by comma, followed by 0 or more whitespace characters, rather than on whitespace. \K : Cause the regex engine to "keep" everything it had matched prior to the \K and not include it in the match. This causes to keep the double quote in @F elements, while comma and whitespace are removed during the split.
-i.bak : Edit input files in-place (overwrite the input file). Before overwriting, save a backup copy of the original file by appending to its name the extension .bak.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perlrequick: Perl regular expressions quick start

Related