我有目錄work_dir,里面有一些子目錄。在子目錄內有 zip 檔案。我可以在終端中看到所有 zip 檔案:
find . -name *.zip
輸出:
./folder2/sub/dir/test2.zip
./folder3/test3.zip
./folder1/sub/dir/new/test1.zip
現在我想用一些選項將所有這些檔案名連接在單行中。例如我想要單行:
my_command -f ./folder2/sub/dir/test2.zip -f ./folder3/test3.zip -f ./folder1/sub/dir/new/test1.zip -u user1 -p pswd1
在此示例中:
my_command是某個命令
-f選項
-u user1另一個具有值的選項 另一個具有值的
-p pswd1選項
你能幫我嗎,我怎么能在 Linux BASH 中做到這一點?
uj5u.com熱心網友回復:
一種方法是:(根據@M. Nejat Aydin 評論更新)
find . -name "*.zip" -print0 | xargs -0 -n1 printf -- '-f\0%s\0' | xargs -0 -n100000 my_command -u user1 -p pswd1
請注意,-n100000引數強制先前 xargs 的所有輸出在同一行上執行,假設結果數量將小于100000.
我使用空終止版本(注意:-0標志,-print0),因為檔案名可以包含空格。
uj5u.com熱心網友回復:
這是一個 bash 腳本,它應該做你想做的事。
#!/usr/bin/env bash
user=user1
passwd=pswd1
while IFS= read -rd '' files; do
args =(-f "$files")
done < <(find . -name '*.zip' -print0)
args=("${args[@]}" -u "$user" -p "$passwd")
##: Just for the human eye to see the output,
##: change this line of code according to the comment below.
printf 'mycommand %s\n' "${args[*]}"
輸出應該是一行,就像你想要的那樣,但要改變最后一行
printf 'mycommand %s\n' "${args[*]}"
進入
mycommand "${args[@]}"
如果你真的想mycommand用引數執行。
也改變userand的值passwd。
- A
while讀取回圈與IFS一起使用。
請參閱如何逐行(和/或逐欄位)讀取檔案(資料流、變數)?
- 為什么最后一行應該改變。見引數
- 在處理檔案/路徑名中的空格時,Shell 參考是一個基本但常見的錯誤。
請參閱如何找到并安全處理包含以下內容的檔案名
還有find命令/實用程式。
- 構造
"${args[@}"是一個陣列。
請參見Array1 Array2 Array3
uj5u.com熱心網友回復:
您可以通過制作 bash 腳本來做到這一點。
- 創建一個名為whatever.sh的新檔案
- 鍵入
chmod x ./whatever.sh使其在終端上可執行 - 添加 BASH 腳本,如下所示。
#!/bin/bash
# Get all the zip files from your FolderName
files="`find ./FolderName -name *.zip`"
# Loop through the files and build your args
arg=""
for file in $files; do
arg="$arg -f $file"
done
# Run your command
mycommand $arg -u user1 -p pswd1
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/503778.html
上一篇:迭代地將字串添加到bash陣列
