This question already has an answer here:
If the arguments are files, I want to change their extensions to .file
.
That's what I got:
#!/bin/bash
while [ $# -gt 0 ]
do
if [ -f $1 ]
then
sed -i -e "s/\(.*\)\(\.\)\(.*\)/\1\2file" $1
fi
shift
done
The script is running, but it doesn't do anything. Another problem is that file hasn't any extension, my sed command will not work, right? Please help.
Using a shell function to wrap a
sed
evaluate (e
) command:Tests, given files bah and boo, and the extension should be .file, which is then changed to .buzz:
Output:
How it works:
while
loop parses each file name separately, since a name might include escaped spaces and whatnot. If the filenames were certain to have not such escaped spaces, thewhile
loop could probably be avoided.sed
reads standard input, provided by abash
here string<<< "$1"
.sed
code changes each name foo.bar (or even just plain foo) to the string "mv -iv foo.bar foo.file" then runs that string with thee
valuate command. The-iv
options show what's been moved and prompts if an existing file might be overwritten.sed is for manipulating the contents of files, not the filename itself.
Option 1, taken from this answer by John Smith:
Option 2, taken from this answer by chooban:
Option 3, taken from this answer by David W.:
and more is here.
UPDATE : (in comment asked what % and {} doing?)
"${variable}othter_chars" > if you want expand a variable in string you can use it. and
%.*
in{}
means take the value of variable strip off the pattern.*
from the tail of the value for example if your variable befilename.txt
"${variable%.*} return justfilename
.