BASH: Split a string without ‘cut’ or ‘awk’

For a little test script I’m writing I needed to split a line on a ‘;’ but preservere the “s and ’s, something that echo doesn’t like to do. Digging deeper into the bash docs I see that there are some handy string handling functions.

#!/bin/bash
line=’this “is” a command;this “is” a pattern’
COMMAND=${line%;*}
PATTERN=${line#*;}
echo $COMMAND
echo $PATTERN

And the output would be:

this “is” a command
this “is” a pattern

14 Responses to “BASH: Split a string without ‘cut’ or ‘awk’”

  1. mads says:

    This one should win a price… I works great and is noce and simple…

  2. kerpz says:

    very nice.
    Tnx for sharing …

  3. Tako says:

    Brilliant. Solved a big one for me

  4. Anonymous says:

    you rock.

  5. RAGHU says:

    EXCELENT, FANTASTIC, DONE

  6. Hameed says:

    Just what I needed!

  7. bart says:

    very nice, used it for a simply archive handling bash script i wrote and put on my site :)

  8. nihilist says:

    The only problem is that it doesn’t deal with multiple instancse of the separator character. What then?

  9. Anton says:

    nihilist,

    Then you break out some perl or sed regex action and break it apart accordingly.

  10. Acácio says:

    Outstanding!

    Very usefull when splitting configuration files like:

    PARAM=VALUE
    PARAM=VALUE
    .
    .
    .

    Congratulations!

  11. Jake says:

    This is so much more elegant than a nasty sed/awk expression. Thanks for improving my code!

  12. Thuktun says:

    Is there a way to get this to work with more than once delimiter present?

  13. rich says:

    Here’s how you could use multiple delimiters.. This is messy and I think there’s a better way but I havent figured it out yet.

    #!/bin/bash

    line=’content,100,2′

    content=${line%%,*}

    delay=${line#*,}

    delay=${delay%,*}

    instance=${line##*,}

    echo $content

    echo $delay

    echo $instance

    I would read more here: http://linuxgazette.net/issue18/bash.html

  14. Anon says:

    Thuktun: If you double the % or #, then it matches as few as it can instead of as much as it can. Example:

    > T=a,b,c,d
    > echo ${T%%,*}
    a
    > echo ${T%,*}
    a,b,c

Leave a Reply