需要帮助使用shell脚本将文件从一个目录移动到另一个目录

时间:2015-06-22 19:58:40

标签: sh

将有一个目录,其中包含各种文件类型(xlsx,gpg,txt)。

如果.gpg然后只调用decrypt.sh或者将文件移动到输出文件夹。

任何可以帮助我的人都会这样做吗?

1 个答案:

答案 0 :(得分:0)

假设bash(可能),您可以使用for命令迭代目录中的文件,例如以下记录:

pax> ls -al
total 4
drwxr-xr-x    5 pax ubergeeks        0 Jun  7 16:01 .
drwxr-xr-x    1 pax ubergeeks     8192 Jun  7 16:01 ..
-rw-r--r--    1 pax ubergeeks        0 Jun  7 16:01 file 1.txt
-rw-r--r--    1 pax ubergeeks        0 Jun  7 16:01 file 2.gpg
-rw-r--r--    1 pax ubergeeks        0 Jun  7 16:01 file 3.xlsx

pax> for fspec in *.txt *.gpg *.xlsx ; do
...>    echo "==> '$fspec'"
...> done
==> 'file 1.txt'
==> 'file 2.gpg'
==> 'file 3.xlsx'

您可以使用正则表达式运算符测试字符串变量是否以特定字符串结尾:

if [[ "${fspec}" =~ \.gpg$ ]] ; then
    echo it ends with .gpg
fi

当然,您可以运行脚本或使用以下命令移动文件:

/path/to/decrypt.sh "${fspec}
mv "${fspec}" /path/to/output

因此,结合所有这些,一个很好的起点就是(确保指定真实路径而不是我的/path/to/占位符):

#!/usr/bin/env bash

cd /path/to/files
for fspec in *.txt *.gpg *.xlsx ; do
    if [[ "${fspec}" =~ \.gpg$ ]] ; then
        echo "Decrypting '${fspec}'"
        /path/to/decrypt.sh "${fspec}"
    else
        echo "Moving '${fspec}'"
        mv "${fspec}" /path/to/output
    fi
done