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
?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With