Bash 添加字符串到文件名

Erw*_*ith 1 macos bash shell

我需要在给定目录中的每个文件名的扩展名之前添加单词“hallo”。但我的代码没有产生任何输出。echo 语句没有给出输出并且文件名没有更改

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
Run Code Online (Sandbox Code Playgroud)

Geo*_*iou 8

使用 bash 可以更简单地完成此操作,例如:

for f in *;do
echo "$f" "${f%.*}hallo.${f##*.}"
done
Run Code Online (Sandbox Code Playgroud)

例子:

$ 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
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为${f%.*}返回不带扩展名的文件名 - 删除从末尾(向后)到第一个/最短找到的点的所有内容(*)。

另一方面,此操作${f##*.}会删除从开头到找到的最长点的所有内容,仅返回扩展名。

要克服评论中指出的无扩展名文件问题,您可以执行以下操作:

$ 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
Run Code Online (Sandbox Code Playgroud)

如果文件没有扩展名,那么这将是 true"${f%.*}" == "${f}"