如何用 \n 替换双引号外的所有空格?

如何用 \n 替换双引号外的所有空格?

我有一个$variable有许多用空格分隔的双引号路径

echo $variable

"/home/myuser/example of name with spaces" "/home/myuser/another example with spaces/myfile"

我的变量上的路径数量可能会有所不同,并且不受控制。例如,它可以类似于以下示例:

example 1: "path1" "path2" "path3" "path4"
example 2: "path1" "path2" "path3" "path4" "path5" "path6" path7" "path8"
example 3: "path1" "path2" "path3" 
example 4: "path1" "path2" "path3" "path4" "path5" "path6"

我想将双引号外的所有空格替换为新行 ( \n),同时保留引号内的空格。使用echo $variable | tr " " "\n"答案对我不起作用,因为它用新行替换了所有空格。我该怎么做?

答案1

如果元素是总是双引号,那么您可以将 quote-space-quote 替换为 quote-newline-quote:

$ sed 's/" "/"\n"/g' <<< "$variable"
"/home/myuser/example of name with spaces"
"/home/myuser/another example with spaces/myfile"

或(使用 shell 参数替换)

$ printf '%s\n' "${variable//\" \"/\"$'\n'\"}"
"/home/myuser/example of name with spaces"
"/home/myuser/another example with spaces/myfile"

但如果您可以修改脚本以使用数组,那就更简单了:

$ vararray=("/home/myuser/example of name with spaces" "/home/myuser/another example with spaces/myfile")
$ printf '"%s"\n' "${vararray[@]}"
"/home/myuser/example of name with spaces"
"/home/myuser/another example with spaces/myfile"

相关内容