2

How to remove the comma (,) between two words?

How can I place those two words in two different rows?

This is my input:

ent0
ent4
ent1,ent5
ent2,ent6
ent3,ent7
ent29,ent30
1
  • 1
    There's a good chance you don't need to, and can set the field separator for the next command to include commas.
    – OrangeDog
    Aug 8, 2017 at 11:15

8 Answers 8

16
tr ',' '\n'

would replace all ,s in your input file with line breaks, that sounds like it is what you want.

6

Use tr:

$  tr ',' '\n' < FILE
ent0
ent4
ent1
ent5
ent2
ent6
ent3
ent7
ent29
ent30
5

Using bash:

#!/bin/bash
while IFS='' read -r line; do 
    echo "${line//,/$'\n'}";
done <infile.txt

or sed

sed -e $'s/,/\\\n/g' infile.txt 

or

sed 's/,/\
/g' infile.txt 
4

In case there may be spaces or other blank characters around the comma - sed solution:

sed 's/[[:blank:]]*,[[:blank:]]*/\
/g' file

With some sed implementations, you can replace the \<newline> with \n.

1

You can use cut as follow:

I don't know where your data come from. But I'm sure you can pipe your info to cut:

cat yourfile.data | cut -d, --output-delimiter ' ' -f 1,2

as per man cut

...
-d, --delimiter=DELIM
       use DELIM instead of TAB for field delimiter
--output-delimiter=STRING
       use STRING as the output delimiter the default is to use the input delimiter
-f, --fields=LIST
       select only these fields;  also print any line that contains no delimiter character, unless the -s option is specified
...

But, if you need to add further logic I recommend you to use sed as @RomanPerekhrest said. You will have a more flexible way to parse your data with powerful regular expressions. In my opinion, the best regular expression for doing this would be:

'/^\s*\([^,]\+\)\s*,\s*([^,]\+\)\s*$/'

~ 0 or more spaces followed of anything but comma, followed of 0 or more spaces, comma, 0 or more spaces followed of anything but comma, followed of 0 or more spaces.

0

In case you'll want to keep the column structure, here's how to only get commas substituted by spaces.

In bash:

while IFS=, read -r field1 field2; do
    printf "%s %s\n" "$field1" "$field2"
done < test.txt

Reference: http://mywiki.wooledge.org/BashFAQ/001

0

With the use of tr(on the specific case that you provided) you can translate the comma to new line

user@server[/test]> cat text.txt
ent0
ent4
ent1,ent5
ent2,ent6
ent3,ent7
ent29,ent30
user@server[/test]> cat text.txt| tr "," "\n"
ent0
ent4
ent1
ent5
ent2
ent6
ent3
ent7
ent29
ent30
0
$ cat /tmp/sample.txt
one,two, three
four, five,six

tr command options:

  • Remove comma (,)
  • Remove newline (\n)
  • Remove empty space (' ')

Below is the output:

$ cat /tmp/sample.txt | tr "," "\n" | tr -d ' '
one
two
three
four
five
six

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .