How to pass files to a script that processes folders
所以我有了这个bash脚本,它将重命名当前目录中的所有文件。我需要帮助修改它,这样我只能指定某些将被重命名的文件,但仍然可以将其传递到目录。我对bash不太熟悉,所以对我来说很困惑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #!/bin/bash # # Filename: rename.sh # Description: Renames files and folders to lowercase recursively # from the current directory # Variables: Source = x # Destination = y # # Rename all directories. This will need to be done first. # # Process each directory’s contents before the directory itself for x in `find * -depth -type d`; do # Translate Caps to Small letters y=$(echo $x | tr '[A-Z]' '[a-z]'); # check if directory exits if [ ! -d $y ]; then mkdir -p $y; fi # check if the source and destination is the same if ["$x" !="$y" ]; then # check if there are files in the directory # before moving it if [ $(ls"$x") ]; then mv $x/* $y; fi rmdir $x; fi done # # Rename all files # for x in `find * -type f`; do # Translate Caps to Small letters y=$(echo $x | tr '[A-Z]' '[a-z]'); if ["$x" !="$y" ]; then mv $x $y; fi done exit 0 |
您的脚本有大量初学者错误,但标题中的实际问题有一些优点。
对于这样的任务,我将使用递归解决方案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | tolower () { local f g for f; do # If this is a directory, process its contents first if [ -d"$f" ]; then # Recurse -- run the same function over directory entries tolower"$f"/* fi # Convert file name to lower case (Bash 4+) g=${f,,} # If lowercased version differs from original, move it if ["${f##*/}" !="${g##*/}" ]; then mv"$f""$g" fi done } |
请注意,包含文件名的变量总是需要加引号(否则,您的脚本将在包含shell元字符的文件名上失败),以及bash如何具有内置功能来降低变量值(在最新版本中)。
另外,切切地说,不要在脚本中使用