Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove double quotes from all fields in an array in bash

Tags:

bash

sed

awk

This array exists in bash script under a minimal linux/posix environment. All the fields in my string array are surrounded by double quotes. I am seeking an elegant solution to removing the double quote character at the beginning and end of each field, as there may be double quotes within the field that should not be removed.

The array is single dimensional, and contains fields as follows:

"This is a value, in this element"
"This is also a "value" but has double quotes"
"0X:41:DE:AD:BE:EF; -- EXIT --"

The desired field values after the operation would be as follows:

This is a value, in this element
This is also a "value" but has double quotes
0X:41:DE:AD:BE:EF; -- EXIT --

Currently I've tried the following without success:

fields=`sed -e 's/^"//' -e 's/"$//' <<<"${fields[@]}"
like image 856
user3665852 Avatar asked Dec 13 '25 11:12

user3665852


1 Answers

Assuming that “in Bash” means “without external processes”, you can apply the usual Bash expansions / transformations to each array element. This yields the desired output, for example:

fields=('"This is a value, in this element"'
        '"This is also a "value" but has double quotes"'
        '"0X:41:DE:AD:BE:EF; -- EXIT --"')
        
fields=("${fields[@]/#\"}")  # remove leading quotes
fields=("${fields[@]/%\"}")  # remove trailing quotes

printf '%s\n' "${fields[@]}"
like image 123
Andrej Podzimek Avatar answered Dec 15 '25 15:12

Andrej Podzimek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!