osx - Bash adding a string to file name -
i need add word "hallo" @ end of each filename before extension in given directory. code produces no output. echo statements give no output , file names not changed
count="" dot="." file in $ls echo $file count="" f in $file echo $f if [ $f -eq $dot ]; count=$count"hallo" fi count=$count+$f done mv $file $count done
with bash can done simplier like:
for f in *;do echo "$f" "${f%.*}hallo.${f##*.}" done
example:
$ 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 $ 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
this works because ${f%.*}
returns filename without extension - deletes (*) end (backwards) first/shortest found dot.
on other hand 1 ${f##*.}
deletes beginning longest found dot, returning extension.
to overcome extensionless files problem pointed out in comments can this:
$ 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
if file has not extension yeld true "${f%.*}" == "${f}"
wiki
Comments
Post a Comment