skip to Main Content

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


  1. What about use mv command?

    mv a.jpg a
    
    Login or Signup to reply.
  2. You can solve your problem by piping the result of find to a while loop:

    # First step - basic idea:
    # Note: requires hardening
    
    find . -type f | while read file; do
        # do some work with ${file}
    done
    

    Next, you can extract a filename without an extension with ${file%.*} and an extension itself with ${file##*.} (see Bash – Shell Parameter Expansion):

    # Second step - work with file extension:
    # Note: requires hardening
    
    find . -type f | while read file; do
        [[ "${file##*.}" == "jpg" ]] && echo "${file%.*}" || echo "${file}";
    done
    

    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 tune read to be able to deal with it:

    # Final step
    
    find . -type f -print0 | while IFS= read -r -d '' file; do
        [[ "${file##*.}" == "jpg" ]] && echo "${file%.*}" || echo "${file}";
    done
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search