首页 > 解决方案 > 如何将此字符串转换为 Bash 中 Python 文件的可交互列表?

问题描述

我有一个字符串如下:

string = '[ "file1.py", "file2.py", "file3.py", "file4.py" ]'

如何将其转换为单个文件名的可迭代列表,以便我可以在其上运行 for 循环,如下所示:

for filen in fileArr
do
    echo $filen
done

预期输出:

file1.py
file2.py
file3.py
file4.py

到目前为止,我刚刚删除了第一个和最后一个方括号,string=${string:1:${#string}-2}但我仍然需要删除引号和逗号。有没有一种干净简单的方法来实现这一目标?

标签: bash

解决方案


您可以使用该tr命令(有关 tr 命令的更多信息,请参见此处)消除开始括号、结束括号和双引号。此外,您可以将逗号替换为选项卡,以便稍后迭代结果。

这里的代码:

$ s='[ "file1.py", "file2.py", "file3.py", "file4.py" ]'
$ s2=$(echo $s | tr "[" " " | tr "]" " " | tr "\"" " " | tr "," "\\t")
$ for x in $s2; do echo $x ; done
file1.py
file2.py
file3.py
file4.py

更深入地,该s2声明使用:

s2=$(          --> Assigns the output of the full command to s2
  echo $s        --> Prints the content of s to the pipes
  | tr "[" " "   --> Substitute the start bracket by spaces
  | tr "]" " "   --> Substitute the end bracket by spaces
  | tr "\"" " "  --> Substitute the double quotations by spaces
  | tr "," "\\t"  --> Substitute the comma by a tab
)

请注意,此代码对您提供的输入类型有效,但如果文件名包含空格,它将不起作用。

编辑:

另一种解决方案是使用子字符串替换而不是使用tr命令。

这里的代码:

$ s2=${s//\[/}  # Erase the start brackets
$ s3=${s2//\]/}  # Erase the end brackets
$ s4=${s3//\"/}  # Erase the double quotations
$ s5=${s4//,/ }  # Substitute the comma by a tab
$ for x in $s5; do echo $x ; done
file1.py
file2.py
file3.py
file4.py

与前面的解决方案一样,请注意,如果文件名包含空格,则代码将不起作用(因为它们将被视为单独的条目)。

编辑2:

正如@Z4-tier 所指出的,第一个选项可以-d使用tr. 此选项会删除给定的字符。此外,如果内部字段分隔符 (IFS) 设置不正确,解析后获得的字符串可能无法迭代。尽管我认为以前的解决方案涵盖了大多数情况,但如果将 IFS 值设置为默认值以外的其他值,您可能会考虑设置和恢复它。

因此,你可以写:

$ s='[ "file1.py", "file2.py", "file3.py", "file4.py" ]'
$ s2=$(echo $s | tr -d "[]\"" | tr "," "\\t")
$ IFS=$' '
$ for x in $s2; do echo $x ; done
file1.py
file2.py
file3.py
file4.py
$ IFS= #restore your IFS value

推荐阅读