0

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

file1.txt
file1.jpg.txt

file2.txt
file2.jpg.txt

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. – roaima Nov 12 '18 at 7:26
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.

-1
#!/bin/bash

## 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
terminal=`tty`
exec < ${delete=delete}
        while read line
        do
                rm -rf $line
        done
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 
terminal=`tty`
exec < ${rename=rename}
        while read line
        do
                nn=`echo $line | sed 's/.jpg//gi'`
                mv $line $nn
        done
exec < $terminal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.