I want to remove the extension of specific files with a given extension.
So for instance, in a directory foobar
, we have foo.txt, bar.txt foobar.jpg
.
Additionally, the extension that I’ve put in to be removed is txt
After calling the program, my output should be foo bar foobar.jpg
Here is my code so far:
#!/bin/bash
echo "Enter an extension"
read extension
echo "Enter a directory"
read directory
for file in "$directory"/*; do //
if [[ $file == *.txt ]]
then
echo "${file%.*}"
else
echo "$file"
fi
done
However when I run this on a given directory, nothing shows up.
I’m assuming that there is a problem with how I referred to the directory ( in the line where I placed a //
) and I’ve tried to research on how to solve it but to no avail.
What am I doing wrong?
3
Answers
If files do exist in a valid directory you’ve entered then they should show up — with one exception. If you are using
~/
(shorthand home directory) then it will be treated as plain text in your for loop. The read variable should be substituted into another variable so thefor loop
can treat it as a directory (absolute paths should work normally as well).You can simplify your for-loop:
The
%
instructions removes only matching characters. If nothing matches, the original string (heref
) is returned.When you write bash scripts it’s more common to pass arguments to your script via command line arguments rather than by reading it from standard input via
read
program.Passing arguments via command line:
This approach is more efficient because a subprocess is spawn for
read
command to run and there is no subprocess spawn for reading command line arguments.There is no need to manually loop through directory, you can use
find
command to find all files with given extension within given directory.Note that to avoid bash filename expansion sometimes it is required to wrap actual pattern in single quotes
' '
or double quotes" "
. See Bash Filename ExpansionSo now your script can look like this:
Construct
${file%.$EXTENSION}
is called Shell Parameter Expansion it searches for occurrence of.$EXTENSION
insidefile
variable and deletes it.Notice that in the script it is easy to pass extension as directory and vice versa.
We can check if second argument is in fact directory, we can use following construction:
This way we can exit from the script earlier with more readable error.
To sum up entire script could look like this:
Example usage: