split a string in bash

Cut a string at a delimiter into parts or an array.

  • shell
  • development

Steps

  1. IFS=, read -r a b c <<< "x,y,z"

    three parts into three variables

  2. IFS=, read -ra parts <<< "$line"

    every part into an array

  3. echo "${parts[1]}"

    the second part (arrays start at 0)

  4. cut -d, -f2 <<< "$line"

    only the second field, with cut

  5. tr ',' '\n' <<< "$line"

    one part a line

Commands used

  • read
  • cut
  • tr

Each has a page in lore: lore read opens it.