简体   繁体   中英

How to Convert String in a Text File into Array in Bash

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM