I was playing with IFS today and created a quick text file with a list of numbers separated by commas on 1 line.


I then tried to write a script to print each number on a newline. I was able to make it work, but I had to know how many fields there were. I'm trying to figure out how to do this on a list that's much longer where I wouldn't want to specify every field.

while read num1 num2 num3 num4 num5
printf $num1"\n"
printf $num2"\n"
printf $num3"\n"
printf $num4"\n"
printf $num5"\n"
printf "\n"
done < "$1"

This gives me the output:

keismbp13b:tmp$ ./ifs.sh list

I'm thinking I may have to use awk or something similar to separate the list onto newlines but I am curious if there is another way.


I also realized just after posting that I could do this

tr , "\n" < list

Is there anyway to do this without separating the list first?


As you pointed in your question it's can be done with tr command as follows:

tr ',' '\n' < infile

and here are other options to do that.

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


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

Or in some sed implementations, use:

sed 's/,/\n/g' infile

Or via awk (if you don't mind last empty line):

awk -v RS=',' '1' infile

Or in bash:

while IFS='' read -r line; do 
    echo "${line//,/$'\n'}";
done < infile

Or reading to an array and then printf:

while IFS=, read -a fields; do
    printf "%s\n" "${fields[@]}";
done < infile
  • considering each field separated with comma as like ..., 2 4, ... at above, else, you can add it to IFS from IFS=',' to IFS=', ' to print in separate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.