我有一个目录中有几个文件和目录。我想将扩展名.ext
添加到所有文件。有些文件有扩展名(不同类型的扩展名),有些文件没有扩展名。如何添加和更改目录中文件的扩展名?
我正在使用Ububtu 16.04。
我读了几个关于它的答案,但我无法理解它们。
我有一个目录中有几个文件和目录。我想将扩展名.ext
添加到所有文件。有些文件有扩展名(不同类型的扩展名),有些文件没有扩展名。如何添加和更改目录中文件的扩展名?
我正在使用Ububtu 16.04。
我读了几个关于它的答案,但我无法理解它们。
在bash:
$ for f in * ; do if [ -f "$f" ] ; then t="${f%.*}" ; mv -i "$f" "$t".ext ; fi ; done
解释:
for f in * # loop all items in the current dir
do
if [ -f "$f" ] # test that $f is a file
then
t="${f%.*}" # strip extension off ie. everything after last .
mv -i "$f" "$t".ext # rename file with the new extension
fi
done
测试:
$ touch foo bar baz.baz
$ mkdir dir ; ls -F
bar baz.baz dir/ foo
$ for f in * ; do if [ -f "$f" ] ; then t="${f%.*}" ; mv -i "$f" "$t".ext ; fi ; done
$ ls
bar.ext baz.ext dir/ foo.ext
一些覆盖可能发生,如果,例如;有文件foo
和foo.foo
。因此我将-i
切换到mv
。一旦你明白了上面的脚本的作用,就将其删除。
它将扩展添加到目录(只剩下问题),这也是我不想做的。它正在向扩展名为。的文件正确添加扩展名。我在前面的问题中错过了目录,现在编辑了它。对不起。 –
'%'被用于去除'。'后的所有内容。 。 –
'%。*'意味着剥离上一期以及之后的所有内容。这也可能会导致一个问题,如果你有一个名为'like.this'和'or.this.txt'的句号为'extensionless'的文件。 –
这是您所需要的:
find . -name "*" -type f|awk 'BEGIN{FS="/"}{print $2}'|awk 'BEGIN{FS=".";ext=".png"}{system("mv "$0" ./"$1ext"")}'
[[email protected] check]# ls -lrt
total 0
-rw-r--r--. 1 root root 0 Oct 5 08:08 abc
-rw-r--r--. 1 root root 0 Oct 5 08:08 hello.txt
-rw-r--r--. 1 root root 0 Oct 5 08:08 something.gz
[[email protected] check]# find . -name "*" -type f|awk 'BEGIN{FS="/"}{print $2}'|awk 'BEGIN{FS=".";ext=".png"}{system("mv "$0" ./"$1ext"")}'
[[email protected] check]# ls -lrt
total 0
-rw-r--r--. 1 root root 0 Oct 5 08:08 abc.png
-rw-r--r--. 1 root root 0 Oct 5 08:08 hello.png
-rw-r--r--. 1 root root 0 Oct 5 08:08 something.png
只是简单的awk命令。应该很容易理解 –
用命令MV像这样的问题: https://stackoverflow.com/questions/6114004/add-file-extension-to-files-with- bash –
它不工作。 –
“它不工作”根本没有帮助......什么“不工作”?它做愚蠢的事情吗?它会给你带来错误吗?你是怎么试过的?显示代码... – Mischa