Search code examples
linuxbashtextcut

How to Split a string and print all the substrings using cut


I have some comma separated strings and want to split them using cut command in bash:

This, is a, sample input.
This, is, another string, which could, appear, in my text, file.

I also want to print all the substrings in the output. The desired output of the first string is:

This
is a
sample input.

and this is the desired output of the second string:

This
is
another string
which could
appear
in my text
file.

but since the number of commas(substrings) is not fixed in all of the strings, I don't know how to tell the cut command to show all the substrings. (for example there 2 commas in the first string and 6 in the second). Is there any way to do this in bash (with cut or other commands)?

I have to add that although my examples in this post are in English, My actual strings are in Arabic language. I mean the command which I want to use, have to be able to work with Unicode characters.


Solution

  • Just because you wanted cut:

    line='This, is a, sample input.'
    for i in $(seq 1 $(echo "$line," | tr -dc ',' | wc -c)); do
      echo $line | cut -d, -f$i; 
    done