I’m trying to create a program that would remove the extensions of files with that specific extension in a directory.
So for instance there exists a directory d1, within that directory there are three files a.jpg, b.jpg and c.txt and the extension that I want to manipulate is .jpg.
After calling my program, my output should be a b c.txt
since all files with .jpg now have jpg removed from them.
Here is my attempt to solve it so far:
#!/bin/bash
echo "Enter an extension"
read extension
echo "Enter a directory"
read directory
allfiles=$( ls -l $directory)
for x in $allfiles
do
ext=$( echo $x | sed 's:.*.::')
if [ $ext -eq $extension]
then
echo $( $x | cut -f 2 -d '.')
else
echo $x
fi
done
However, when I run this, I get an error saying
'-f' is not defined
'-f' is not defined
what should I change in my code?
2
Answers
What about use
mv
command?You can solve your problem by piping the result of
find
to awhile
loop:Next, you can extract a filename without an extension with
${file%.*}
and an extension itself with${file##*.}
(see Bash – Shell Parameter Expansion):The final step is to introduce some kind of hardening. Filenames may contain "strange" characters, like a new line character or a backslash. We can force
find
to print the filename followed by a null character (instead of the newline character), and then tuneread
to be able to deal with it: