Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to insert line breaks in a file whenever a comma is encountered-Shell script

Tags:

shell

unix

awk

I need to write a shell script to re-format a file by inserting line breaks. The condition is that a line break should be inserted when we encounter comma in the file.

For example, if the file delimiter.txt contains:

this, is a file, that should, be added, with a, line break, when we find, a comma.

The output should be:

this
is a file
that should
be added
with a
line break
when we find a
a comma.

Can this be done grep or awk?

like image 235
Shreedhar Avatar asked Aug 28 '13 11:08

Shreedhar


2 Answers

Using GNU sed:

sed 's/, /\n/g' your.file

Output:

this
is a file
that should
be added
with a
line break
when we find a
a comma. 

Note: the syntax above will work only on system that have the \n as line delimiter as Linux and the most UNIXes.

If you need a portal solution in a a script then use the following expression that uses a literal new line instead of \n:

sed 's/,[[:space:]]/\
/g' your.file

Thanks @EdMorten for this advice.

like image 192
hek2mgl Avatar answered Oct 03 '22 19:10

hek2mgl


This is what tr is for

$ tr ',' '\n' <<< 'this, is a file, that should, be added, with a, line break, when we find, a comma.'
this
 is a file
 that should
 be added
 with a
 line break
 when we find
 a comma.

Or if you must use awk:

awk '{gsub(", ", "\n", $0)}1' delimiter.txt
like image 36
user000001 Avatar answered Oct 03 '22 19:10

user000001