Using printf
Statement
Use the printf
statement to convert the array to a comma-separated string in Bash.
1 2 3 4 5 |
array=("Jan" "Feb" "Mar" "Apr") printf -v joined '%s,' "${array[@]}" echo "${joined%,}" |
1 2 3 |
Jan,Feb,Mar,Apr |
We initialized an array
containing string elements. Then, we used the printf
statement to convert the specified array to a comma-separated string. How? The printf
statement formatted and stored the elements of the array
into the joined
variable, which we specified using the -v
parameter.
In the printf
statement, the "%s"
was the format specifier for strings, which told that every element of the array
must be printed as a string value and followed by a comma. The "${array[@]}"
expanded the array
data into individual elements, which would be formatted via a printf
statement.
So, the printf -v joined '%s,' "${array[@]}"
line essentially concatenated the items of the array
into a string separating every item with a comma. Finally, we used the echo
command to print the value of the joined
variable with the last comma (trailing comma) removed.
In the echo
command, the "${joined%,}"
expanded the value of the joined
variable and removed the trailing comma using the ${parameter%,}
syntax; here, the parameter
was the joined
variable. Here, the %
character was used as a pattern to remove the trailing comma.
Alternatively, if you don’t want to use the -v
parameter, you can store the comma-separated string into a variable as follows.
1 2 3 4 5 |
array=("Jan" "Feb" "Mar" "Apr") array=$(printf '%s,' "${array[@]}") echo "${array%,}" |
1 2 3 |
Jan,Feb,Mar,Apr |
This example is similar to the previous one, but we used syntax substitution syntax here. First, we used the substitution syntax represented by the $(...)
to capture the output of the printf
statement, which was further assigned to the array
variable; finally, we displayed it on the Bash console using the echo
command.
In both examples, the delimiter, a comma (
,
) in our case, is preceded by the%s
.
Using awk
Command
Use the awk
command to convert an array to a comma-separated string in Bash.
1 2 3 4 5 6 7 8 9 |
array=("Jan" "Feb" "Mar" "Apr") awk -v sep=',' 'BEGIN{ ORS=OFS=""; for(i=1;i<ARGC;i++){ print ARGV[i],ARGC-i-1?sep:"" } }' "${array[@]}" |
1 2 3 |
Jan,Feb,Mar,Apr |
After initializing the array
variable, we used the awk command to convert the given array into a comma-separated string. Let’s break down the use of the awk
command to understand it.
We used the -v
parameter to set the value of the sep
variable; we used a comma as a delimiter and initialized the sep
variable with a comma. Then, we used the awk
script enclosed within the single quotes, which was run before processing the input. Following is a brief explanation of each component within the script.
- The
BEGIN
is anawk
pattern, specifying the actions/operations to be performed before input processing. Here, theORS=OFS=""
set the ORS (Output Record Separator) and OFS (Output Field Separator) to the empty string, ensuring that no extra characters would be added between the items while printing them on the console. - The
for
loop was used to iterate over the given arguments to theawk
command. Theprint
statement within the loop printed the current argument (ARGV[i]
) followed by the specified separator (sep
). However, it printed an empty string rather than the separator for the last element using the ternary operator (ARGC-i-1?sep:""
). - We used the
"${array[@]}"
to expand thearray
into separate items, which were passed as arguments to theawk
command. These were the arguments on which theawk
script iterated and printed them, followed by the given separator.
This way, the array
was converted to comma-separated strings; you can see the output above.
Using IFS Shell Variable
Use IFS (Internal Field Separator), a shell variable, to convert the specified array to a comma separated strings in Bash.
1 2 3 4 5 6 |
array=("Mon" "Tue" "Wed") IFS=, output="${array[*]}" echo "$output" |
1 2 3 |
Mon,Tue,Wed |
First, we declared and initialized the array
containing three string elements. Then, we set the value of IFS, a particular shell variable, to a comma; this value would be used to separate the strings.
After that, we used parameter expansion to expand the array into separate items and joined them with the IFS
separator, which we explicitly specified. Finally, we assigned the comma-separated strings to the output
variable, which was further used with the echo
command to display the results on the console.
Alternatively, we can do as follows:
1 2 3 4 |
array=("Mon" "Tue" "Wed") (IFS=,; echo "${array[*]}") |
1 2 3 |
Mon,Tue,Wed |
This example is comparable to the last one. Here, in the second line of code, we created a subshell represented by (...)
, which was executed to temporarily modify the value of the IFS
variable and printed the comma-separated string using the echo
command. Note that the semi-colon was used to separate the commands from one another.
Why did we create a subshell to mutate the IFS value and expand the array elements? Because we want to ensure that the changes would be temporary and not affect the rest of the script. Using this approach, you can convert the array
into a comma-separated string by temporarily mutating the value of the IFS
variable and expanding the array elements using parameter expansion ("${array[*]}"
).
What to do to split the array into a comma-separated string without mutating the IFS
variable? In that use case, we can use the following approach, which will only work as expected if the IFS
variable is not mutated and set to its default value, a space character.
1 2 3 4 5 |
array=("Mon" "Tue" "Wed") expandedArrayStr="${array[*]}" echo "${expandedArrayStr//${IFS:0:1}/,}" |
1 2 3 |
Mon,Tue,Wed |
Again, we created an array named array
having three string-type elements. Then, we used parameter expansion syntax to expand the array into a string and stored it in the expandedArrayStr
variable. Finally, we used the echo
command to print the comma-separated string on the Bash console. Let’s understand how a string was transformed into a comma-separated string.
In the echo "${expandedArrayStr//${IFS:0:1}/,}"
command:
- The
${IFS:0:1}
expression expanded to the first character of theIFS
variable, which by default contained a whitespace character, including a tab, newline, and a space. This extracted a substring from theIFS
beginning at index0
with a length of1
. Since theIFS
was a single character, so we retrieved the first character ofIFS
effectively. - The
${expandedArrayStr//${IFS:0:1}/,}
expression was a parameter expansion with a pattern substitution (whose syntax was${inputString//pattern/replacement}
). This expression substituted all occurrences of the given pattern (${IFS:0:1}
, the first character ofIFS
) in theexpandedArrayStr
with replacement (,
).
Using this, all occurrences of theIFS
‘s first character inexpandedArrayStr
would be replaced with a comma, effectively converting the array to a comma-separated string. - Finally, the
echo
command printed the results on the Bash console.
You must convert the array to a string to use this approach.
Using for
Loop
To transform an array to a comma-separated string in Bash:
- Declare and initialize an array containing string items.
- Use the
for
loop to iterate over an expanded array. The array is expanded using parameter expansion. - In each iteration of
for
, we used the+=
operator to join the current element followed by a comma. - Use the
echo
command with${parameter%,}
syntax to remove the trailing command and print the values on the bash console.
1 2 3 4 5 6 7 8 9 |
array=("grapes" "guava" "orange") output="" for element in "${array[@]}" do output+="$element," done echo "${output%,}" |
1 2 3 |
grapes,guava,orange |
Here we used a for
loop to join all elements.
That’s all about how to convert Array to Comma Separated String in Bash.