
我有 10 個具有連續名稱的資料夾:book_1、book_2..... book_10,每個資料夾都有一個與該資料夾名稱相同的 txt 檔案。例如:book_1 有僅有的book_1.txt 包含歷史資料(僅限文字)。
我需要運行一個 AWK 腳本,該腳本的輸出應按順序添加到輸出檔案中。如何產生一個循環,該循環運行我的資料夾並從每個資料夾中提取所需的檔案?
awk '
{
script//
}
END { print "The output of book num $i is: " m }' book*/book*.txt >> output.txt // m is a variable which extracts max occurences of certain words which are set in the script
我的輸出應該是這樣的:
The output of book num 1 is : 123
The output of book num 2 is : 2223
等等
感謝您的幫忙!
答案1
{1..10}
在支援產生一系列數字的構造的 shell 中使用任何 awk 的簡單方法(否則只需使用$(seq 10)
)是:
for i in {1..10}; do
awk -v i="$i" '
{
script//
}
END { printf "The output of book num %d is : %d\n", i, m }
' "book_${i}/book_${i}.txt"
done > output.txt
但如果你真的想在 awk 中完成這一切(使用 GNU awk 作為 ARGIND 和 ENDFILE):
awk '
BEGIN {
for (i=1; i<=10; i++) {
ARGV[ARGC] = "book_" i "/book_" i ".txt"
ARGC++
}
}
{
script//
}
ENDFILE { printf "The output of book num %d is : %d\n", ARGIND, m; m=0 }
' > output.txt
如果任何「book」檔案不存在,那麼您需要添加一些保護措施。