シェルスクリプトに複数のIF条件を持つForループ

シェルスクリプトに複数のIF条件を持つForループ

まず、/tmp/testファイルパスに次のディレクトリがあります。

amb
bmb
cmb

このコマンドを実行すると、これらの3つのディレクトリに次のファイルのfindリストが表示されます。

amb/eng/canon.amb
bmb/eng/case.bmb
cmb/eng/hint.cmb

list1ループを使用して、forファイルの種類に応じて各ファイルをインポートしようとします。それ*.amb以外の場合は、*.bmb特定の*.cmbIFを実行する必要があります。

cd /tmp/test
find */ -type f -exec ls {} \; > /tmp/test/list1
for file in `cat /tmp/test/list1`
do
if [ -f *.amb ]
then
sed "s/amb/amx/g" /tmp/test/list1 > /tmp/test/list2
ls /tmp/test/list2 >> /tmp/test/finallist
fi

if [ -f *.bmb ]
then
sed "s/bmb/bmx/g" /tmp/test/list1 > /tmp/test/list2
ls /tmp/test/list2 >> /tmp/test/finallist
fi

if [ -f *.cmb ]
then
sed "s/cmb/cmx/g" /tmp/test/list1 > /tmp/test/list2
ls /tmp/test/list2 >> /tmp/test/finallist
fi

done
echo "*********************"
echo -e "\nFinal list of files after replacing from tmp area"
felist=`cat /tmp/test/finallist`

echo -e "\nfefiles_list=`echo $felist`"

したがって、最終出力は次のようになります。

amx/eng/canon.amx
bmx/eng/case.bmx
cmx/eng/hint.cmx

ベストアンサー1

ファイルのサフィックスによって異なる操作を適用しようとしているようです。

#!/bin/bash
while IFS= read -d '' -r file
do
    # amb/eng/canon.amb
    extn=${file##*.}

    case "$extn" in
    (amb)   finallist+=("${file//amb/amx}") ;;
    (bmb)   finallist+=("${file//bmb/bmx}") ;;
    (cmb)   finallist+=("${file//cmb/bmx}") ;;
    esac
done <( cd /tmp/test && find */ -type f -print0 2>/dev/null )

printf '*********************\n\n'
printf 'Final list of files after replacing from tmp area\nfefiles_list=%s\n' "${finallist[*]}"

さて、

  • find */ -type f -exec ls {} \; > /tmp/test/list1find */ -type f -print > /tmp/test/list1すでに表示されているので、作成することをお勧めします。find */ -type f > /tmp/test/list1しかし、これは奇妙な(しかし正当な)ファイル名を壊します。
  • バックティックは使用されなくなり、代わりにバックティックを使用する必要があります$( … )。ただし、スペースやその他の特殊文字を含むファイル名は破損します。

おすすめ記事