I want to split a text with comma ,
not space in
for foo in list
. Suppose I have a CSV file CSV_File
with following text inside it:
Hello,World,Questions,Answers,bash shell,script
...
I used following code to split it into several words:
for word in $(cat CSV_File | sed -n 1'p' | tr ',' '\n')
do echo $word
done
It prints:
Hello
World
Questions
Answers
bash
shell
script
But I want it to split the text by commas not spaces:
Hello
World
Questions
Answers
bash shell
script
How can I achieve this in bash?
You can use:
or
This is the part that replace comma with space
Using a subshell substitution to parse the words undoes all the work you are doing to put spaces together.
Try instead:
That also increases parallelism. Using a subshell as in your question forces the entire subshell process to finish before you can start iterating over the answers. Piping to a subshell (as in my answer) lets them work in parallel. This matters only if you have many lines in the file, of course.
Set IFS to ,:
Read: http://linuxmanpages.com/man1/sh.1.php & http://www.gnu.org/s/hello/manual/autoconf/Special-Shell-Variables.html
IFS is a shell environment variable so it will remain unchanged within the context of your Shell script but not otherwise, unless you EXPORT it. ALSO BE AWARE, that IFS will not likely be inherited from your Environment at all: see this gnu post for the reasons and more info on IFS.
You're code written like this:
should work, I tested it on command line.
I think the canonical method is:
If you don't know or don't care about how many fields there are:
Create a bash function
... this generates the following output:
(Note, this answer has been updated according to some feedback)