使用 shell 脚本在 Unix 服务器中重命名具有相同文件名模式的文件
我在UNIX服务器中有一些具有相同文件名模式的文件。
例子: 样本:
ABC DE FGH IJKL 04012022.csv
ABC DE FGH IJKL 04022022.csv
预期输出:
ABC_DE_FGH_IJKL_04012022.csv
ABC_DE_FGH_IJKL_04022022.csv
这是我尝试的。但是在MV命令中遇到了错误,因为它试图一次重命名两个文件。
for file in ls ABC\ DE\ FGH\ IJKL\ ????????.csv
do
#Extracting date part separately
date_part=$(ls ABC\ DE\ FGH\ IJKL\ ????????.csv | cut -c 17-24)
#Appending date part to file
csv_file_nm="ABC_DE_FGH_IJKL_"$date_part.csv
#Renaming file using mv command
mv ABC\ DE\ FGH\ IJKL\ ????????.csv $csv_file_nm
done
I have a few files with the same file name pattern in the Unix server.
Example:
Sample:
ABC DE FGH IJKL 04012022.csv
ABC DE FGH IJKL 04022022.csv
Expected Output:
ABC_DE_FGH_IJKL_04012022.csv
ABC_DE_FGH_IJKL_04022022.csv
This is what I tried. But got an error in the mv command as it was trying to rename both files at once.
for file in ls ABC\ DE\ FGH\ IJKL\ ????????.csv
do
#Extracting date part separately
date_part=$(ls ABC\ DE\ FGH\ IJKL\ ????????.csv | cut -c 17-24)
#Appending date part to file
csv_file_nm="ABC_DE_FGH_IJKL_"$date_part.csv
#Renaming file using mv command
mv ABC\ DE\ FGH\ IJKL\ ????????.csv $csv_file_nm
done
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
显示的代码被严重打破:
要使用此想法(这不是一个很好的程序方式,但是…),您需要在循环中使用
“ $ file”
而不是重复ls
操作:该脚本使用球形而不是
ls
生成文件名 - 我从ls
中删除了ls
行。您可能打算在$(ls…)中为文件编写,或者可能在`
'中写下文件 - 但这不是问题。也不建议处理
ls
的输出。但是,由于您想用下划线替换空间,因此一种更直接的操作方法是:
或者,如果您的外壳是bash(足够新的),则:
或者,如果您具有基于Perl的
Rename < /code>(有时称为
prename
)在系统上命令,然后:The code shown is horribly broken:
To use this idea (which isn't a very good way of proceeding, but…), you'd need to use
"$file"
in the loop rather than repeatedls
operations:That script uses globbing rather than
ls
to generate the file names — I've removed a strayls
from thefor
line. You might have intended to write forfile in $(ls …)
, or maybe forfile in `ls …`
— but that isn't in the question. Processing the output ofls
is not recommended either.However, since you want to replace the spaces with underscores, a more direct way of operating would be:
Or, if your shell is Bash (and new enough), then:
Or, if you have the Perl-based
rename
(sometimes calledprename
) command on the system, then: