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
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityHow 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
tr ',' '\n'
would replace all ,
s in your input file with line breaks, that sounds like it is what you want.
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
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
.
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.
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
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
$ cat /tmp/sample.txt
one,two, three
four, five,six
tr command options:
Below is the output:
$ cat /tmp/sample.txt | tr "," "\n" | tr -d ' '
one
two
three
four
five
six