如何在 bash 中剥离和拆分包含转义序列的字符串?

How to strip and split a string which contains an escape sequence in bash?

我有一个字符串。例如

STR="          Hello, World    I'm\ new\ here  "

而我想要接收的是这样一个数组

"Hello,"
"World"
"I'm new here"

或者至少是一些可迭代的东西,这样我就可以迭代这些“词”并对它们进行操作。谢谢!

如果您不介意使用更多步骤的解决方案,您可以使用

echo "          Hello, World    I'm\ new\ here  " |
  sed 's/\ /\r/g' | grep -Eo "[^ ]*" | sed 's/\r/ /g'

少一个管道使正则表达式更复杂:

echo "          Hello, World    I'm\ new\ here  " | 
  grep -Eo "([^ ]*([\] )*)+[^ ]*" | sed 's/\ / /g'

使用 GNU sed 你可以有不同的方法:

echo "          Hello, World    I'm\ new\ here  " |
  sed -z 's/ /\n/g; s/\\n/ /g' | grep .

您可以简单地使用 read

$ STR="          Hello, World    I'm\ new\ here  "
$ read -a x <<< "$STR"
$ declare -p x
declare -a x=([0]="Hello," [1]="World" [2]="I'm new here")

read 照常对其输入进行分词; -a 选项导致每个单词存储为数组的单独元素,而不是将单词存储在单独的变量中。 read 的默认行为是用它们代表的字符替换转义序列:在这种情况下,'\ ' 代表 ' '.