我有一个包含数千个文件的目录,每个文件都有一个副本。一个例子:
file1.txt
file1.jpg.txt
file2.txt
file2.jpg.txt
我想删除所有 *.txt 文件,并保留 *.jpg.txt 然后我想将所有 *.jpg.txt 重命名为 *.txt
我在 OpenSuse 12 上运行
答案1
正如@roaima 提到的,您不需要首先删除文件,移动文件时您会自动覆盖旧文件。
一种方法是在 bash 中使用 for 循环:
for f in *.jpg.txt; do mv $f ${f/%.jpg.txt/.txt}; done
让我解释:
for f in *.jpg.txt; do <command>; done
:对 的每个文件执行命令*.jpg.txt
。执行时文件名存储在变量中f
。${f/%.jpg.txt/.txt}
: 的值$f
,但最后出现的.jpg.txt
被替换为.txt
。看https://www.tldp.org/LDP/abs/html/parameter-substitution.html了解更多这方面的例子。mv $f ${f/%.jpg.txt/.txt}
:将旧文件重命名为新文件名,不带.jpg
.
在运行此代码之前,您可以通过运行来向自己保证它会做正确的事情
for f in *.jpg.txt; do echo $f ${f/%.jpg.txt/.txt}; done
这将打印出将移动的文件对。
答案2
#!/bin/bash
## to remove ".txt" files
# this will keep the files which removing in txt
# you can see delete file on the script path
ls -lrth | grep ".txt" | grep -v "jpg" | awk -F' ' {'print $9'} > delete
terminal=`tty`
exec < ${delete=delete}
while read line
do
rm -rf $line
done
exec < $terminal
## Renaming the files
# this will keep the files which we are renaming
# you can see rename file on the script path
ls -lrth | grep -i "jpg" | awk -F' ' {'print $9'} > rename
terminal=`tty`
exec < ${rename=rename}
while read line
do
nn=`echo $line | sed 's/.jpg//gi'`
mv $line $nn
done
exec < $terminal