You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写脚本复制*.txt为*.new.txt并忽略已存在的该类文件

批量复制TXT文件并跳过已存在的目标文件

直接用find+-exec实现(推荐)

这是处理含特殊字符文件名最稳妥的方式,直接在find命令里完成逻辑:

find ~/folder -type f -name "*.txt" ! -name "*.new.txt" -exec sh -c '
  for file do
    # 构造目标文件名:把原文件的.txt替换成.new.txt
    target="${file%.txt}.new.txt"
    # 仅当目标文件不存在时执行复制
    if [ ! -f "$target" ]; then
      cp "$file" "$target"
    fi
  done
' sh {} +

关键逻辑说明

  • ${file%.txt}.new.txt:用参数扩展语法替换文件名后缀,比如note.txt会变成note.new.txt
  • [ ! -f "$target" ]:检查目标文件是否存在,不存在才执行复制,满足你“忽略已存在*.new.txt”的需求
  • -exec ... {} +:把find找到的所有文件批量传给shell脚本,比逐个处理更高效

用xargs替代的写法

如果习惯用xargs,也可以这么写:

find ~/folder -type f -name "*.txt" ! -name "*.new.txt" | xargs -I {} sh -c '
  target="${0%.txt}.new.txt"
  [ ! -f "$target" ] && cp "$0" "$target"
' {}

封装成可复用脚本

把逻辑保存成copy_txt.sh,方便重复运行:

#!/bin/bash

# 可以修改这里的目标目录
SOURCE_DIR=~/folder

find "$SOURCE_DIR" -type f -name "*.txt" ! -name "*.new.txt" -exec sh -c '
  for file do
    target="${file%.txt}.new.txt"
    if [ ! -f "$target" ]; then
      echo "复制文件: $file -> $target"
      cp "$file" "$target"
    fi
  done
' sh {} +

给脚本添加执行权限后就能直接运行:

chmod +x copy_txt.sh
./copy_txt.sh

内容的提问来源于stack exchange,提问作者azgardweb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 09:18:25