Alp Alt
Alp Alt

Reputation: 33

Bash, how to delete unique filenames?

In a folder there are .mp4 files; and .txt files which containing text info about .mp4 files, with same filename. But there are some .mp4 files without text file. I want to delete only these (unique) .mp4 files, is there an easy way to do it in Bash (Ubuntu14.04) ?

Example:

001.mp4
001.txt
002.mp4
002.txt
003.mp4
004.mp4
004.txt

I want to delete only 003.mp4 from folder.

Upvotes: 0

Views: 121

Answers (2)

ceving
ceving

Reputation: 23794

A list based approach.

This generates a list of all txt files having the extension .txt striped off:

basename -as.txt *.txt

The same for the mp4 files:

basename -as.mp4 *.mp4

grep can be used to subtract two lists. This is the list of mp4 files, without the txt files:

basename -as.mp4 *.mp4 | grep -vf <(basename -as.txt *.txt)

And xargs can be used to execute commands on lists:

basename -as.mp4 *.mp4 |
grep -vf <(basename -as.txt *.txt) |
xargs -i rm {}.mp4

Upvotes: 0

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

Echo to see first which files will be deleted

for file in *.mp4 ; do [[ -f ${file%.mp4}.txt ]] || echo "file not found ${file%.mp4}.txt"; done

Remove files

for file in *.mp4 ; do [[ -f ${file%.mp4}.txt ]] || /usr/bin/rm "${file}"; done

Or depending where command rm is located and to avoid using alias

for file in *.mp4 ; do [[ -f ${file%.mp4}.txt ]] || \rm "${file}"; done

Upvotes: 2

Related Questions