【问题标题】:How to pass files to a script that processes folders如何将文件传递给处理文件夹的脚本
【发布时间】:2017-09-16 11:01:36
【问题描述】:

所以我有这个 bash 脚本,它将重命名当前目录中的所有文件。我需要帮助来修改它,这样我就可以只指定某些将被重命名的文件,但仍然可以将它传递给一个目录。我对 bash 不是很熟悉,所以这让我很困惑。

#!/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

【问题讨论】:

标签: bash file recursion directory


【解决方案1】:

您的脚本有大量初学者错误,但标题中的实际问题有一些优点。

对于这样的任务,我会选择递归解决方案。

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 如何具有 built-in functionality for lowercasing a variable's value(最近版本)。

另外,切线,don't use ls in scripts 并在寻求人工调试帮助之前尝试http://shellcheck.net/

【讨论】:

    猜你喜欢
    • 2023-01-23
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 2013-01-07
    相关资源
    最近更新 更多