Skip to content

How to Split comma separated values in bash

Sometimes can be handy to be able to split comma separated values using bash, especially if we don’t want to pass an infinite amount of arguments ending up in finishing all the keyboard letters. With this small how to we will show how to split comma separated values in bash

Solution 1: IFS

IFS is a special shell variable (Internal Field Separator) that determines how Bash recognizes word delimiters.

IFS=","
INPUT=$1
read -ra array <<< "$INPUT"
for item in "${array[@]}"
do
    echo "$item"
done

# exmaple usage
sh split.sh 1,2,3,4,5
1
2
3
4
5

Solution 2: AWK

AWK is an extremely powerful text processing tool

INPUT=$1
awk -F',' '{ for( item=1; item<=NF; item++ ) print $item }' <<<"$INPUT"

# exmaple usage
sh split.sh a,b,c,d,e,f
a
b
c
d
e
f

Solution 3: Using the parameters expansion

If you don’t want to deal with IFS and awk, there is a third solution, using the parameter expansion that the shell can offer to us.

INPUT=$1
arr=(${INPUT//","/ })
for item in "${arr[@]}";
do
  echo "$item"
done

# exmaple usage
sh split.sh a,b,c,d,e,f
a
b
c
d
e
f

Hope this will help you solving your problem

Share this content:

0
Would love your thoughts, please comment.x
()
x