Reputation: 121
I have set FS for awk as FS = "," but it is still using space as delimiter. After using below code it has created 3 array elemnets, one for commma and other for space. Please suggest how can I restrict awk to not use space as FS
Code :
arr_values=(`awk 'BEGIN{FS = ","}
{for (i=0; i<=NF; i++)
print $i
};
END{}' File`)
for ((i=0; i<${#arr_values[@]}; i++))
do
echo ${arr_values[$i]}
done
content of File :
1, abc def
Output :
abc
def
1
abc
def
Upvotes: 0
Views: 212
Reputation: 3646
First, quotes should be surrounding command substitution to prevent unwanted word splitting. When command output expands into an array unquoted, each whitespace delimited field gets separated into its own element.
Also, as jas mentioned, the Awk loop should be initializing i
to 1
not 0
. The $0
record in Awk is the entire line, which is why the array contains duplicates.
However, quoting variables won't do what you want:
$ arr_values=("$(awk -F', ' '{for (i=1; i<=NF; i++) print $i}' File)")
$ echo "${arr_values[0]}"
1
abc def
The newline is preserved here but is all contained a single element of the array because the quotes enclose the entire command substitution output.
To accomplish what you want, use the Bash builtin readarray
. It will read each line from standard input into a separate array element:
$ readarray -t arr_values < <(awk -F', ' '{for (i=1; i<=NF; i++) print $i}' File)
$ for ((i=0; i<${#arr_values[@]}; i++)); do echo "${arr_values[$i]}"; done
1
abc def
Upvotes: 3