在 Linux 中删除文件名中的某些字符
Remove certain characters in a filename in Linux
我在
等目录中有文件
FILE1.docx.txt
FILE2.docx.txt
FILE3.docx.txt
FILE4.docx.txt
FILE5.docx.txt
我想从所有这些中删除 .docx
以使最终输出如
FILE1.txt
FILE2.txt
FILE3.txt
FILE4.txt
FILE5.txt
我该怎么做?
只是 运行 这个 python 脚本在包含文件的同一文件夹中:
import os
for file in os.listdir(os.getcwd()):
aux = file.split('.')
if len(aux) == 3:
os.rename(file, aux[0] + '.' + aux[2])
for f in *.docx.txt; do
echo mv -vn "$f" "${f%%.*}.${f##*.}"
done
一线
for f in *.docx.txt; do echo mv -vn "$f" "${f%%.*}.${f##*.}"; done
如果您认为输出正确,请删除 echo
以重命名文件。
应该可以在任何 POSIX
兼容的 shell 中工作,无需任何脚本。
使用 bash,启用 nullglob
shell 选项,这样如果没有以.docx.txt
#!/usr/bin/env bash
shopt -s nullglob
for f in *.docx.txt; do
echo mv -vn "$f" "${f%%.*}.${f##*.}"
done
更新:感谢 @Léa Gris
添加 nullglob
将 glob 更改为 *.docx.txt
并将 -n
添加到 mv
,尽管 -n
和-v
没有按照 https://pubs.opengroup.org/onlinepubs/9699919799/utilities/mv.html 由 POSIX
定义 它应该在 GNU 和 BSD 中都存在 mv
您可以像这样使用 sed 和 bash:
for i in *.docx.txt
do
mv "$i" "`echo $i | sed 's/.docx//'`"
done
我在
等目录中有文件FILE1.docx.txt
FILE2.docx.txt
FILE3.docx.txt
FILE4.docx.txt
FILE5.docx.txt
我想从所有这些中删除 .docx
以使最终输出如
FILE1.txt
FILE2.txt
FILE3.txt
FILE4.txt
FILE5.txt
我该怎么做?
只是 运行 这个 python 脚本在包含文件的同一文件夹中:
import os
for file in os.listdir(os.getcwd()):
aux = file.split('.')
if len(aux) == 3:
os.rename(file, aux[0] + '.' + aux[2])
for f in *.docx.txt; do
echo mv -vn "$f" "${f%%.*}.${f##*.}"
done
一线
for f in *.docx.txt; do echo mv -vn "$f" "${f%%.*}.${f##*.}"; done
如果您认为输出正确,请删除 echo
以重命名文件。
应该可以在任何 POSIX
兼容的 shell 中工作,无需任何脚本。
使用 bash,启用 nullglob
shell 选项,这样如果没有以.docx.txt
#!/usr/bin/env bash
shopt -s nullglob
for f in *.docx.txt; do
echo mv -vn "$f" "${f%%.*}.${f##*.}"
done
更新:感谢 @Léa Gris
添加 nullglob
将 glob 更改为 *.docx.txt
并将 -n
添加到 mv
,尽管 -n
和-v
没有按照 https://pubs.opengroup.org/onlinepubs/9699919799/utilities/mv.html 由 POSIX
定义 它应该在 GNU 和 BSD 中都存在 mv
您可以像这样使用 sed 和 bash:
for i in *.docx.txt
do
mv "$i" "`echo $i | sed 's/.docx//'`"
done