如何循環執行多個文件

如何循環執行多個文件

我有一個腳本,其功能對於一個文件來說是這樣的。

./script 0001g.log > output

對於兩個或多個文件,像這樣

./script 0001g.log 0002g.log 0003g.log > output

該腳本從每個輸入檔案中獲取一個特殊數字並將其放入一個輸出檔案中。

我的問題是我有 1000 個輸入文件,如何循環執行我的腳本。

答案1

您有幾種可能的解決方案:

簡單地

$ ./script *g.log >output

...並希望這*g.log不會擴展到使命令行太長的情況。這不是很穩健。

如果您的腳本不依賴為其提供的文件數量,即如果可以將輸出附加到output每個輸入文件,那麼這是另一個解決方案:

$ find ./ -type f -name "*g.log" | xargs ./script >output

第三種解決方案是將循環移至腳本本身:

for f in *g.log; do
  # old code using "$f" as file name
done

這不存在命令行長度限制的問題,因為它位於腳本中。

腳本的呼叫現在是

$ ./script >output

答案2

如果

./script 0001g.log 0002g.log 0003g.log > output

等式

./script 0001g.log > output
./script 0002g.log >> output
./script 0003g.log >> output

那你可以使用循環或

`seq -f '%04gg.log' 10` | script > output

答案3

如果您願意,可以將文件放入目錄中

/opt/location/source
    /0001g.log
    /0002g.log
    /0003g.log

然後在你的 bash 腳本中你可以嘗試以下操作

#!/bin/bash

# store path to files
SOURCE="/opt/location/source/"

# loop through files
for FILE in `ls $SOURCE*g.log`; do
    # do what you want to specific file
    echo $FILE
done

相關內容