Search code examples
bashshellunixkshcut

String separation in unix shell


STRINGS=str1,str2,str3

I want each string seperated by space as given below:

STRING1=`echo $STRINGS | cut -d',' -f1` ==> gives "str1"

REMAINING_STRING=`echo $STRINGS | cut -d',' -f2- | 
    sed -e 's/,/ /g'` ==> gives "str2 str3"

But when the string contains only one entry, for e.g STRINGS=str1 , then REMAINING_STRING is also populating with same value as STRING1. I want REMAINING_STRING to be null when the STRINGS contain only one entry.

STRINGS=str1

STRING1=`echo $STRINGS| cut -d',' -f1` ==> gives "str1"

REMAINING_STRING=`echo $STRINGS | cut -d',' -f2- | sed -e 's/,/ /g'`

==> gives "str1", But this should come as null.

How to do this in unix shell?


Solution

  • $ STRINGS=str1
    $ echo $STRINGS | cut -d',' -f2- | sed -e 's/,/ /g'
    str1
    $ echo $STRINGS | cut -s -d',' -f2- | sed -e 's/,/ /g'
    $
    

    Explanation of -s from the man page.

       -s, --only-delimited
              do not print lines not containing delimiters