Bash shell for 迴圈過程,有兩個成對的變數名

Bash shell for 迴圈過程,有兩個成對的變數名

例如,通常使用 bash shell 批次重命名大量檔案。通常我會使用以下結構,

for file in ./*.short
do
# do command
done

這適用於副檔名為 .short 的檔名。但是,現在如何在命令中處理兩個或多個變數名稱(在本例中為檔案副檔名)?我想對以下命令進行批量處理,

( x2x +sf < data.short | frame -l 400 -p 80 | \
bcut +f -l 400 -s 65 -e 65 |\
window -l 400 -L 512 | spec -l 512 |\
glogsp -l 512 -x 8 -p 2 ;\
\
bcut +f -n 20 -s 65 -e 65 < data.mcep |\
mgc2sp -m 20 -a 0.42 -g 0 -l 512 | glogsp -l 512 -x 8 ) | xgr

在這種情況下,我想同時處理 .short 和 .mcep。我用邏輯 (&&) 但它不起作用,

for file1 in ./*.short && ./*.mcep
do
# $file1 and file2 process
done

任何經驗豐富且熟練的 shell 程式設計師想分享如何解決這個問題嗎?我有使用嵌套循環的想法,但我不知道如何在 Bash 中實現。

答案1

您可以循環遍歷 *.shorts,然後使用以下命令檢查對應的 *.mcep 檔案:

#!/bin/bash

for i in *.short
do
   base=${i%%?????}
   if [ -e ${base}mcep ]
   then
      echo ${base}.short
      echo ${base}.mcep
   fi
done

我只是在此處呼應了 *.short 和 *.mcep 名稱,但您現在可以在命令中使用它們。

答案2

你可以使用這個腳本

#!/bin/bash

for file1 in /path/to/files/*
do
    ext=${file#*.}

    if [[ "$ext" == "mcep" ]]
    then 
        #command to run on files with 'mcep' extension
    elif [[ "$ext" == "short" ]]
    then
        #command to run on files with 'short' extension
    fi
done

答案3

#!/bin/bash

for file in ./*.short 
do
(x2x +sf < $file | frame -l 400 -p 80 | 
bcut +f -l 400 -s 65 -e 65 |
window -l 400 -L 512 | spec -l 512 |
glogsp -l 512 -x 8 -p 2 ;\

bcut +f -n 20 -s 65 -e 65 < ${file%.short}.mcep |\
mgc2sp -m 20 -a 0.42 -g 0 -l 512 | glogsp -l 512 -x 8 ) | psgr > ${file%.short}.eps
done

相關內容