webgoudarzi
webgoudarzi

Reputation: 81

Shell Script Search and Delete Non Text Files

I want to write a shell script to search and delete all non text files in a directory..

I basically cd into the directory that I want to iterate through in the script and search through all files.

-- Here is the part I can't do --

I want to check using an if statement if the file is a text file. If not I want to delete it else continue

Thanks

PS By the way this is in linux

EDIT

I assume a file is a "text file" if and only if its name matches the shell pattern *.txt.

Upvotes: 2

Views: 925

Answers (3)

ghostdog74
ghostdog74

Reputation: 342313

find . -type f ! -name "*.txt" -exec rm {} +;

Upvotes: 0

Matthew Iselin
Matthew Iselin

Reputation: 10670

Use the opposite of, unless an if statement is mandatory:

find <dir-path> -type f -name "*.txt" -exec rm {} \;

What the opposite is exactly is an exercise for you. Hint: it comes before -name.

Your question was ambiguous about how you define a "text file", I assume it's just a file with extension ".txt" here.

Upvotes: 0

Barry Kelly
Barry Kelly

Reputation: 42152

The file program always outputs the word "text" when passed the name of a file that it determines contains text format. You can test for output using grep. For example:

find -type f -exec file '{}' \; | grep -v '.*:[[:space:]].*text.*' | cut -d ':' -f 1

I strongly recommend printing out files to delete before deleting them, to the point of redirecting output to a file and then doing:

rm $(<filename)

after reviewing the contents of "filename". And beware of filenames with spaces, if you have those, things can get more involved.

Upvotes: 5

Related Questions