如何在 Bash 中使用以空格作为参数的逗号分隔路径?

How to use comma separated paths with whitespace as arguments in Bash?

我有一个动态路径列表,每个路径本身可能包含也可能不包含空格。例如,

$ STRING='./my text1.txt,./my text2.txt'

我的最终目标是将这些路径作为命令的参数输入,比如 cat:

$ cat "./my text1.txt" "./my text2.txt"
cat: ./my text1.txt: No such file or directory  # this is expected!
cat: ./my text2.txt: No such file or directory

所以我尝试了:

$ STRING='./my text1.txt,./my text2.txt'
$ SEP="\"${STRING//,/\" \"}\""
$ echo $SEP
"my text1.txt" "my text2.txt"
$ cat $SEP                          
cat: "my text1.txt" "my text2.txt": No such file or directory

在上面的示例中,请注意 "my text1.txt" "my text2.txt" 被识别为单个参数。

我的问题是,给定 STRING,我需要做什么才能使 catSEP 识别为两个单独的参数?

谢谢。


上下文

为了向您提供有关上下文的更多信息,我正在尝试为 Github 操作编写脚本以集成 SwiftFormat and changed-files

- name: Get list changed files
  id: changed-files
  uses: tj-actions/changed-files@v17
  with:
    files: |
      **/*.swift

- name: Format Swift code
  run: swiftformat --verbose ${{ steps.changed-files.outputs.all_changed_files }} --config .swiftformat

所以我假设给出了 STRING 并且手动转义空格(例如 ./my\ text1.txt)对我来说不是一个选项。

假设您的文件名没有 space/glob 个字符,您可以使用:

str='./my text1.txt,./my text2.txt'
printf '%s\n' "${str//,/ }" | xargs cat

如果您的文件名可以包含空格,则使用以下两种解决方案中的任何一种:

(IFS=, read -ra arr <<< "$str"; cat "${arr[@]}")

awk -v ORS='[=11=]' '{gsub(/,/, ORS)} 1' <<< "$str" | xargs -0 cat

您必须将 , 上的字符串拆分成一个数组。

string='./my text1.txt,./my text2.txt'
IFS=, read -r -a files  <<<"$string"
cat "${files[@]}"

readarray -t -d '' files < <(tr ',' '[=11=]' <<<"$string")
cat "${files[@]}"