![如何用標準輸入的輸入取代部分檔名?](https://rvso.com/image/178489/%E5%A6%82%E4%BD%95%E7%94%A8%E6%A8%99%E6%BA%96%E8%BC%B8%E5%85%A5%E7%9A%84%E8%BC%B8%E5%85%A5%E5%8F%96%E4%BB%A3%E9%83%A8%E5%88%86%E6%AA%94%E5%90%8D%EF%BC%9F.png)
假設我有一個ids.txt
包含多個條目的文件,例如
foo
bar
bam
...
例如。我想使用它作為輸入來對文件名中包含 ids 的某些文件運行命令,例如foo_1.gz
, foo_2.gz
, bar_1.gz
, bar_2.gz
, ... 等等。
我嘗試引用輸入,{}
因為我看到它與另一個命令一起使用,如下所示:
cat ids.txt | xargs my.command --input1 {}_1.gz --input2 {}_2.gz
但它總是給我這個錯誤:
{}_1.gz no such file or directory
有什麼方法可以將輸入cat
視為字串並自動將它們插入輸入檔案名稱嗎my.command
?
問題還在於my.command
每次都需要兩個輸入文件,所以我不能只使用帶有真實文件名的列表而不是ids.txt
.
答案1
您需要使用-I
此處的選項:
$ cat ids.txt | xargs -I{} echo my.command --input1 {}_1.gz --input2 {}_2.gz
my.command --input1 foo_1.gz --input2 foo_2.gz
my.command --input1 bar_1.gz --input2 bar_2.gz
my.command --input1 bam_1.gz --input2 bam_2.gz
或者,使用 shell 循環:
while read id; do
my.command --input1 "${id}"_1.gz --input2 "${id}"_2.gz
done < ids.txt
這是假設您的 ID 沒有空格或反斜線。如果可以的話,請改用這個:
while IFS= read -r id; do
my.command --input1 "${id}"_1.gz --input2 "${id}"_2.gz
done < ids.txt
最後,您還可以使用每行包含兩個檔案名稱的清單:
$ cat ids.txt
foo_1.gz foo_2.gz
bar_1.gz bar_2.gz
bam_1.gz bam_2.gz
現在:
while read file1 file2; do
my.command --input1 "$file1" --input2 "$file2"
done < ids.txt