I have a directory containing thousands of files, each file has a duplicate. An example:



I want to delete all *.txt files, and leave the *.jpg.txt then afterwards I want to rename all *.jpg.txt to *.txt only

I am running on OpenSuse 12

  • 1
    You don't necessarily need to delete the set of of files before applying the rename. This will allow you to match on *.jpg.txt. There are many "rename" questions and answers here on Unix & Linux so use those as a starting point. Nov 12, 2018 at 7:26

2 Answers 2


As @roaima mentioned, you do not need to first remove the files, when moving the files you would automatically overwrite the old files.

One approach to this is to use a for loop in bash:

for f in *.jpg.txt; do mv $f ${f/%.jpg.txt/.txt}; done

Let me explain:

  • for f in *.jpg.txt; do <command>; done: Execute command on each file of *.jpg.txt. While executing the filename is stored in variable f.
  • ${f/%.jpg.txt/.txt}: The value of $f, but the last occurrence of .jpg.txt is replaced with .txt. See https://www.tldp.org/LDP/abs/html/parameter-substitution.html for more examples of this.
  • mv $f ${f/%.jpg.txt/.txt}: Do the renaming of the old file to the new file name without the .jpg.

Before running this code, you can assure yourself, that it will to the right thing by running

for f in *.jpg.txt; do echo $f ${f/%.jpg.txt/.txt}; done

This will print out the pairs of files that will be moved.


## to remove ".txt" files

# this will keep the files which removing in txt
# you can see delete file on the script path
ls -lrth | grep ".txt" | grep -v "jpg" | awk -F' ' {'print $9'} > delete
exec < ${delete=delete}
        while read line
                rm -rf $line
exec < $terminal

## Renaming the files
# this will keep the files which we are renaming
# you can see rename file on the script path
ls -lrth | grep -i "jpg" | awk -F' ' {'print $9'} > rename 
exec < ${rename=rename}
        while read line
                nn=`echo $line | sed 's/.jpg//gi'`
                mv $line $nn
exec < $terminal

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .