【问题标题】:Moving files with whitespaces and rename, if files already exist in the new folder如果新文件夹中已存在文件,则使用空格移动文件并重命名
【发布时间】:2021-02-25 12:52:01
【问题描述】:

我需要将名称为source (new file).c 的文件移动到另一个目录,如果该文件已经存在,则将其重命名。

我尝试了很多类似的东西

for file in $(find ~/path/ -type f -name "*.c"); do

或

IFS=$'\0' for file in $(find ~/path/ -type f -name "*.c"); do

Update.1 对于重命名条件,我尝试if [ -f /this/is/the/path/${file} ]; then 或if [ -f "$file" ]; then

或if [ -f "$HOME/some/path/$file" ]; then

我想要像read -p "some messege" msg 这样的用户输入,但我想不通,if 语句也不能正常工作,我不知道为什么......

修复它当我运行脚本时,我收到拆分名称的错误。例子: mv: cannot stat '(new': No such file or directory

有人可以帮我解决这个问题吗?

Update.2 使用空格查找名称的解决方案:find ... | while IFS= read -r name; do your command done

Update.3 针对 if 条件如何不起作用的解决方案:检查正确的 awnser

我的遗憾

【问题讨论】:

  • 您可以接受重命名目录中的原始文件而不是新文件吗?
  • 我希望用户在那里输入,所以唯一的问题是在 if 条件下获取文件的全名,以便我可以修改。示例:如果文件不存在只是 mv,如果文件存在询问您是否要保留它 (mv) 或重命名它,它适用于所有其他文件,但不适用于空格。就是这样。
  • 复制/粘贴您的代码(包括#!/bin/bash(或其他))到shellcheck.net 并修复在那里发现的任何问题。 99% 的情况下,您需要在变量名上使用 dbl-quotes,即 "$file"。祝你好运。
  • @shellter 非常感谢,我有一些改进,但问题与空格有关。
  • 对不起,我没有时间设置来测试这个。但是在文件名中使用括号可能会导致比使用空格更多的问题。从这个问题中学习,让你的.c 代码遵循使用_ 字符而不是空格的约定,并且没有其他非字母数字!祝你好运!

标签: linux bash find mv


【解决方案1】:

请您尝试以下方法:

#!/bin/bash

path="/path/to/the/source"      # original directory
dest="/path/to/the/dest"        # destination directory

find "$path" -type f -name "*.c" -print0 | while IFS= read -r -d "" file; do
    f=${file##*/}       # extracts filename by removing everything before "/"
    if [[ -f $dest/$f ]]; then
                        # if the file already exists
        for ((;;)); do  # then enter a infinite loop until proper filename is given
            IFS= read -p "'$f' already exists. Input new name: " f2 < /dev/tty
            if [[ ! $f2 =~ [[:alnum:]_] ]]; then
                echo "'$f2' is not a valid filename."
            elif [[ ! -f $dest/$f2 ]]; then
                        # a proper filename is input
                break
            else        # the filename still exists
                f=$f2
            fi
        done
    fi
    mv -- "$file" "$dest/$f2"
done
  • find ... -print0 使用空字符作为文件名分隔符 保护包含空白的文件名(空格、制表符、换行符...) 字符。
  • read -d "" 对应于 -print0 并将输入拆分为空字符。
  • read &lt; /dev/tty 避免与最外层管道冲突 由find 命令提供。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-20
    • 2020-09-17
    • 1970-01-01
    • 2014-12-27
    • 2015-05-11
    • 1970-01-01
    • 2012-10-14
    相关资源
    最近更新 更多