How to Split comma separated values in bash

How to Split comma separated values in bash

Views: 10
0 0
Read Time:1 Minute, 1 Second

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.

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

happy How to Split comma separated values in bash
Happy
0 %
sad How to Split comma separated values in bash
Sad
0 %
excited How to Split comma separated values in bash
Excited
0 %
sleepy How to Split comma separated values in bash
Sleepy
0 %
angry How to Split comma separated values in bash
Angry
0 %
surprise How to Split comma separated values in bash
Surprise
0 %

Share this content:

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x