更新时间:2022-05-07 22:27:16
使用bash可以简化以下操作:
With bash this can be done simplier like:
for f in *;do
echo "$f" "${f%.*}hallo.${f##*.}"
done
示例:
$ ls -all
-rw-r--r-- 1 29847 29847 0 Aug 21 14:33 file1.txt
-rw-r--r-- 1 29847 29847 0 Aug 21 14:33 file2.txt
-rw-r--r-- 1 29847 29847 0 Aug 21 14:33 file3.txt
-rw-r--r-- 1 29847 29847 0 Aug 21 14:33 file4.txt
-rw-r--r-- 1 29847 29847 0 Aug 21 14:33 file5.txt
$ for f in *;do mv -v "$f" "${f%.*}hallo.${f##*.}";done
'file1.txt' -> 'file1hallo.txt'
'file2.txt' -> 'file2hallo.txt'
'file3.txt' -> 'file3hallo.txt'
$ ls -all
-rw-r--r-- 1 29847 29847 0 Aug 21 14:33 file1hallo.txt
-rw-r--r-- 1 29847 29847 0 Aug 21 14:33 file2hallo.txt
-rw-r--r-- 1 29847 29847 0 Aug 21 14:33 file3hallo.txt
之所以有效,是因为 $ {f%.*}
返回不带扩展名的文件名-从末尾(向后)删除所有(*)直到找到的第一个/最短点.
This works because ${f%.*}
returns filename without extension - deletes everything (*) from the end (backwards) up to first/shortest found dot.
另一方面,这个 $ {f ## *.}
删除从开始到找到的最长点的所有内容,仅返回扩展名.
On the other hand this one ${f##*.}
deletes everything from the beginning up to the longest found dot, returning only the extension.
要克服注释中指出的无扩展名文件问题,您可以执行以下操作:
To overcome the extensionless files problem as pointed out in comments you can do something like this:
$ for f in *;do [[ "${f%.*}" != "${f}" ]] && echo "$f" "${f%.*}hallo.${f##*.}" || echo "$f" "${f%.*}hallo"; done
file1.txt file1hallo.txt
file2.txt file2hallo.txt
file3.txt file3hallo.txt
file4 file4hallo
file5 file5hallo
如果文件没有扩展名,则将产生正确的"$ {f%.*}" =="$ {f}"
If the file has not an extension then this will yeld true "${f%.*}" == "${f}"