需要递归BASH脚本来遍历文件夹并使用通配符

时间:2012-10-05 06:15:33

标签: bash recursion command-line options

我们一直在捕获文件并将文件发送到REST服务器,并将它们从工具栏保存到PNG扩展,现在有近五十万个文件。

最近我们发现他们实际上已经保存为base64流式文件,而不是PNG格式。

我有一个python脚本可以转换它们但不是递归的并且不能使用通配符。

ImageMagick表示base64文件太大(最多5K),因此无法进行转换。

 IE;  /bin/base64-to-png.py <base64_file_name>.png <output_name.png>

目录路径/ mnt / s3 / pages /其中“pages”有几千个编号的文件夹。

 IE; /mnt/s3/pages/100 

   "pages" subfolders are never more than 1 folder deep.
   The files are typically 5540_thumb.png, 5540_snapshot.png and 5540_crop.png 
   where the 5540 is the capture number.

我需要一个BASH脚本包装器使其在文件夹中重复使用,将所有原件复制到备份文件(filename.b64)并将通配符作为正确的路径/名称传递给python脚本,转换文件并保留输出文件然后使用mogrify来压缩它们。

 IE;  base64-to-png.sh *_snapshot.b64 *_snapshot.png <compression number>

  should

    cp <file_name.png> <file_name>.b64
    /bin/base64-to-png.py <file_name.png> <file_name.png>
    mogrify -quality <compression number> -format png <file_name.png>

2 个答案:

答案 0 :(得分:0)

试试这个脚本

#!/bin/bash
SEARCHPATH=$1
COMNUM=$2
FINDEXT="*.png"

for f in `find $SEARCHPATH -type f -name $FINDEXT` ; do
     #just get files name without extension
     fname=`echo $f | cut -d'.' -f1` 
     #perform operations
     cp $f ${fname}.b64
     /bin/base64-to-png.py $f $f
     mogrify -quality $COMNUM -format png $f

done

您可以将其称为

$ base64-to-png.sh /somepath/tofind 100

param 1 : path where to find `.png` files 
param 2 : compression number.

这假设/bin/base64-to-png.py可以在绝对路径上工作,例如/somepath/somedir/somefile.png不只是somefile.png

警告:没有QA完成,请将其用于您的风险!

答案 1 :(得分:0)

将文件名从png更改为base64:

shopt -s globstar
shopt -s nullglob

for file in *.png **/*.png; do
    if (file "${file}" | fgrep "ASCII" >/dev/null 2>&1); then
        # File is named '.png' but is ASCII, move it.
        b64name="${file%.*}.b64"
        mv -f "${file}" "${b64name}"

        # Insert command that converts $b64name to $file

        # I think this will work
        base64 -d "${b64file}" > "${file}" || echo "Conversion failed for ${b64file}"
        mogrify -quality  -format png "${file}"
    fi
done

由于像globstar之类的东西,我相信这需要bash 4.0+。您可以使用bash --version

找到您的版本

如果你使用python进行base64转换至关重要,可以随意交换命令。