Views: 28
0 0
Read Time:1 Minute, 6 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. 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

cc4ae2d7d0e2367495d9f75c31beef8e?s=400&d=robohash&r=g How to Split comma separated values in bash

About Post Author

brewedbrilliance.net

Experienced software architect with a spasmodic passion for tech, software, programming. With more than 20years of experience I've decided to share all my knowledge in pills through this blog. Please feel free to contact me if there is any topic that you would love to cover
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:

By brewedbrilliance.net

Experienced software architect with a spasmodic passion for tech, software, programming. With more than 20years of experience I've decided to share all my knowledge in pills through this blog. Please feel free to contact me if there is any topic that you would love to cover

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