Bash在文件名中添加字符串 [英] Bash adding a string to file name
问题描述
在给定目录中的扩展名之前,我需要在每个文件名的末尾添加单词"hallo".但是我的代码没有输出.echo语句不提供任何输出,文件名也不会更改
I need to add the word "hallo" at the end of each filename before extension in the given directory. but my code produces no output. the echo statements give no output and the file names are not changed
count=""
dot="."
for file in $ls
do
echo $file
count=""
for f in $file
do
echo $f
if [ $f -eq $dot ];
then
count=$count"hallo"
fi
count=$count+$f
done
mv $file $count
done
推荐答案
使用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}"
这篇关于Bash在文件名中添加字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!