Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I'm passing data from STDIN into an array using read like so:

prompt$ cat myfile
a "bc" "d e" f
prompt$ read -a arr < myfile

But read doesn't appear to pay attention to the quoted strings and provides me an array of 5 elements:

prompt$ echo ${#arr[@]}
5
prompt$ echo ${arr[@]:0}
a "bc" "d e" f
prompt$ echo ${arr[2]}
"d
prompt$ echo ${arr[3]}
e"

I'm using the default IFS setting: \t\n in bash. There are several ways to accomplish task using different tools, but I'm surprised that read doesn't support quoted strings.

Any other suggestions for getting a delimited list with quotes into an array?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

I can't think of a very good way to do what you are asking for, but, if you know that your input file is going to contain space-separated tokens that are valid syntax for bash, then something like the following could work:

declare -a arr="($(<myfile))"
share|improve this answer
    
Thank you for mentioning declare. I'm hesitant to use eval much, but it seems that cat myfile | { while read -r; do declare -a "arr=($REPLY)"; done} will get the job done. – Mr. Dave yesterday
    
At the heart of it, declare -a "arr=($MYVAR)" will do the same with a variable. – Mr. Dave yesterday
    
1_CR: Wow, yes, this makes the command a lot less horrible. I will integrate this into my answer. – dhag yesterday

Use this:

IFS=$'\n' arr=( $(xargs -n1 <file) )
  • IFS=$'\n' sets bashs internal field separator to newline.
  • arr=( ... ) the array definition.
  • xargs -n1 <file xargs reads the file with a maximum of 1 argument. The string in quotes stay together, because they are read as arguments.

The output (one element per line):

$ printf "%s\n" "${arr[@]}"
a
bc
d e
f
share|improve this answer
    
Nice, I hadn't thought of using xargs, which does respect quotes. – dhag yesterday
    
@dhag xargs can be used by more cases than just to build commands from stdin =) – chaos yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.