【问题标题】:mv: prompt to rename or overwritemv:提示重命名或覆盖
【发布时间】:2021-02-25 05:59:05
【问题描述】:
find /home/csuser/testfiles . -type f -name "*.c" -exec mv '{}' /home/csuser/src/ \;

上面的命令只会覆盖同名的文件。对于目标中已存在的每个文件名,如何让mv 提示我覆盖现有文件或替换它?

【问题讨论】:

  • 坏主意。通常你会在改变目录树结构时破坏一些东西。 cp -r /home/csuser/{testfiles,src}; find /home/csuser/src/ -type f -not -name "*.c" -delete 将保留所有原始 *.c 文件以及目录结构
  • 你能给这个问题一个合适的标题并将现有的标题移动到主线程中。
  • 在 mv 命令中添加 -i

标签: linux bash ubuntu rename


【解决方案1】:

这是一个简单的 shell 脚本包装器,用于提示您输入每个现有文件。

find /home/csuser/testfiles . -type f -name "*.c" -exec sh -c '
    for file; do
        dest=$0/${file##*/}
        if [ -e "$dest" ]; then
            ls -ld "$dest" "$file"
            read -p "Enter new name for the second, or just ENTER to overwrite the first: " newname
            if [ "$newname" != "" ]; then
                dest=$0/${newname##*/}
            fi
        fi
        mv "$file" "$dest"
    done' /home/csuser/src/ {} +

我们隐蔽但方便地将目标目录作为$0 传递。

【讨论】:

  • 第二个 'do' 错误,我将其更改为 'then' ,它可以工作,但随后它在带有 { } + 的 'done' 行显示错误。我也不明白“-exec sh -c '”和我的“-exec mv '{}'”的区别。非常感谢你的时间兄弟。
  • 请不要叫我“兄弟”。你说得对,应该是then,而不是do。简单的exec mv 显然不会调用read -p
  • 最后一个fi也放错地方了;对此感到抱歉。
  • 如果您的find 真的很旧,它可能不支持-exec ... {} +。你可以切换到-exec ... {} \;,但这有点效率和优雅。
  • 好吧,我已经按照你说的做了。之前的错误已经解决。现在我看到我有一个目的地问题,因为它没有显示任何目的地。正如你所说,我用我的路径替换了 $0:dest=/home/csuser/Desktop/src/${file##*/} but 没有结果。我究竟做错了什么?而且你说的fi你放错了正确的地方是什么?
【解决方案2】:

mv 命令 (man mv) 的联机帮助页显示以下条目:

       -i, --interactive
              prompt before overwrite

因此,在覆盖之前使用mv -i ... 提示。

【讨论】:

  • 这仅允许您在不想覆盖时取消复制。
猜你喜欢
  • 2011-06-21
  • 1970-01-01
  • 2015-11-23
  • 1970-01-01
  • 2016-06-17
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多