Katjoek
Katjoek

Reputation: 381

Bash: convert line to array while keeping consecutive spaces in items

There have been plenty of posts about how to convert a line into an array in Bash. I did not find one that answered my question: how does one do the conversion when items can have consecutive spaces and you don't want those collapsed into a single character?

Example input line: a bcd "ef gh" " ijk "

Expected array items: "a", "bcd", "ef gh", " ijk "

So the last one should NOT be " ijk ", which is the result when using the standard arr=$(line) solution.

It is acceptable to me when consecutive whitespace characters between the arguments in the input line are collapsed.

The example is really just an example. The input line will be read from file containing many different lines to be converted.

Any thoughts?

Upvotes: 0

Views: 65

Answers (1)

chepner
chepner

Reputation: 531135

Partially contradicting my comment, if you modify your input file to look like

a bcd ef\ gh \ \ \ ijk\ \ \ 

then

while read -a arr; do
    printf "%s\n" "${arr[@]}"
done < file.txt

would preserve the escaped spaces the way you want. (Without -r, read will only peform word splitting on the unescaped spaces.) Unlike normal shell processing, "ef gh" here is not equivalent to ef\ gh.


The solution I referred to in my comment would be a more heavily modified input file:

a
bcd
ef gh
   ijk   
#
l m
n op
#
q r s
  tu v

and a loop like

while :; do
    arr=()
    while IFS= read -r element; do
        if [[ element = #* ]]; then
            # do something with arr here
            break
        fi
        arr+=("$element")
    done
done < file.txt

Upvotes: 1

Related Questions