我有一個動態路徑串列,每個路徑本身可能包含也可能不包含空格。例如,
$ 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,我需要將什么cat識別SEP為兩個單獨的論點?
謝謝。
語境
為了向您提供有關背景關系的更多資訊,我正在嘗試為 Github Actions 撰寫一個腳本以集成SwiftFormat和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)不是我的選擇。
uj5u.com熱心網友回復:
Assuming that your filenames don't have space/glob characters you can use:
str='./my text1.txt,./my text2.txt'
printf '%s\n' "${str//,/ }" | xargs cat
In case your file names can contain whitespaces then use any of these 2 solutions:
(IFS=, read -ra arr <<< "$str"; cat "${arr[@]}")
awk -v ORS='\0' '{gsub(/,/, ORS)} 1' <<< "$str" | xargs -0 cat
uj5u.com熱心網友回復:
You have to split the string on , into an array.
string='./my text1.txt,./my text2.txt'
IFS=, read -r -a files <<<"$string"
cat "${files[@]}"
or
readarray -t -d '' files < <(tr ',' '\0' <<<"$string")
cat "${files[@]}"
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/440728.html
下一篇:sed:分段資料中的模式搜索
