【发布时间】:2020-05-23 01:51:34
【问题描述】:
我有一个包含数百个图像文件的目录,每个文件的名称不同,例如:
abdogf.png
abcatf.png
abhorsef.png
我创建了一个 changenames.csv 文件,其中包含两列,第一列是 oldstring,第二列是 newstring,例如:
“狗”,“汪”
"猫","喵喵"
“马”、“嘶”
这些字符串目前用引号引起来,如图所示。
我想从命令行调用 bash 命令或 .sh 脚本,用目录文件名(不在文件内容中)中的每个新字符串子字符串替换每个旧字符串子字符串,这样目录新包含的文件称为:
abwooff.png
abmiaowf.png
abneighf.png
而不是原始文件。
我尝试了各种解决方案,例如https://superuser.com/questions/508731/find-and-replace-string-in-filenames/508758#508758 和How to find and replace part of filenames from list,但均未成功。
例如,我尝试在包含文件的目录中调用以下内容:
#!/bin/bash
inputfile=${1}
while read line
do
IFS=',' read -a names <<< "${line}"
for file in `find . -maxdepth 1 -type f -name "*${names[0]}*"`; do
rename "s/${names[0]}/${names[1]}/" *
done
done < ${inputfile}
使用命令行命令 test.sh changenames.csv。
这不会产生错误,但不会更改文件名。
我也试过这个解决方案https://stackoverflow.com/a/55866613/10456769,它产生了一个错误,其中@echo 不是一个可识别的命令。
提前感谢您的帮助。
【问题讨论】:
-
您尝试过的实际代码和收到的(不正确的)结果是什么?
-
#!/bin/bash inputfile=${1} while read line do IFS=',' read -a names find . -maxdepth 1 -type f -name "*${names[0]}*"; do rename "s/${names[0]}/${names[1]}/" * done done
-
继续更新你的问题,不要把细节埋在 cmets 里
-
然后我尝试@echo off setlocal enabledelayedexpansion for /f "tokens=1,* delims=," %%i in (myfile.csv) do ( set "search=%%i" set " replace=%%j" call :fix ) exit /b :fix for %%a in (!search!.wav) do ( set "file=%%a" set "file=!file :%search%=%replace%!!" echo ren "%%~fa" "!file!" ) 错误 ./test2.sh: line 1: @echo: command not found ./test2.sh: line 2: setlocal:找不到命令 ./test2.sh:第 3 行:意外标记附近的语法错误
"tokens=1,* delims=,"' ./test2.sh: line 3:for /f "tokens=1,* delims=," %%i in (myfile.csv) do (' -
添加一对
echo语句以验证您的rename命令是否符合您的预期。尝试运行打印的重命名命令以确保它有效。调试:-)
标签: bash shell replace rename batch-rename