0

I have text file containing quotes inside single quotes. They are "not" one liners. eg there may be two quotes in same line, but all quotes are inside single quotes like

'hello world' 'this is the second quotes' 'and this is the third quoted text'

how can I create an array and making each quoted text an element of the array. I've tried using

declare -a arr=($(cat file.txt))

but that makes it space separated. assigns each word an element in the array

6
  • 1
    eval arr=($(cat file))? Commented Jun 20, 2019 at 20:04
  • eval?... nice try though Commented Jun 20, 2019 at 20:11
  • Unless the quoted strings can contain newlines, I would just put each string (sans quotes) on a separate line, and use readarray to populate your array. Commented Jun 20, 2019 at 20:29
  • I don't believe there's a way to do that without security vulnerabilities. Commented Jun 20, 2019 at 21:24
  • @DennisWilliamson ahhh? you've got to be kidding right? Commented Jun 21, 2019 at 0:06

1 Answer 1

1

If you have bash v4.4 or later, you can use xargs to parse the quoted strings and turn them into null-delimited strings, then readarray to turn that into a bash array:

readarray -t -d '' arr < <(xargs printf '%s\0' <file.txt)

If you have an older version of bash, you'll have to create the array element-by-element:

arr=( )
while IFS= read -r -d '' quote; do
  arr+=( "$quote" )
done < <(xargs printf '%s\0' <file.txt)

Note that xargs quote syntax is a little different from everything else (of course). It allows both single- and double-quoted strings, but doesn't allow escaped quotes within those strings. And it probably varies a bit between versions of xargs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.