Judy
Judy

Reputation: 1879

search recursive files with type of data that ended with specific extension in order to delete the files

We want to search and delete the data files that ended with extension of .pppd

We can search the files as

find  $path -type f -name '*.pppd' -delete

but how to tell to find command to filter only the data files?

Example how to verify if file is data ( by file command )

file /data/file.pppd
/data/file.pppd: data

file command from manual page

NAME
     file — determine file type

SYNOPSIS
     file [-bchiklLNnprsvz0] [--apple] [--mime-encoding] [--mime-type] [-e testname] [-F separator] [-f namefile] [-m magicfiles] file ...
     file -C [-m magicfiles]
     file [--help]

Upvotes: 2

Views: 93

Answers (3)

Inian
Inian

Reputation: 85875

You can use the find command with the exec option to launch an explicit subshell that runs a shell loop to compare the output type.

find "$path" -type f \
             -name '*.pppd' \
             -exec bash -c 'for f; do [[ $(file -b "$f") = "data" ]] && echo "$f"  ; done' _ {} +

This Unix.SE answer beautifully explains how the -exec bash -c option works with the find command. To briefly explain how it works, the result of find command based on the filter conditions ( -name, -type and -path ) are passed as positional arguments to the loop run under exec bash -c '..'. The loop iterates over the argument list ( for f is analogous to for f in "$@" ) and prints only the files whose type is data. Instead of parsing the result of file, use file -b to get the type directly.

Upvotes: 3

hek2mgl
hek2mgl

Reputation: 158230

You have to launch a shell:

find "${path}" \
    -type f \
    -name '*.pppd' \
    -exec bash -c 'test "$(file "${1}"|awk -F: "{print \$NF}")" = "data"' -- {} \; \
    -print

Upvotes: 3

Matias Barrios
Matias Barrios

Reputation: 5054

You can do it like this. you can change empty regex for a valid Bash regex like for instance ^data and the txt extension for what you want to search for :

#!/bin/bash

read -a files <<< $(find  . -type f -name '*.pppd' )
for file in "${files[@]}"
do
    [[ "$(file -b $file )" =~ ^empty ]] && echo $file
done

If you want to delete the file :

[[ "$(file -b $file )" =~ ^empty ]] || rm "$file"

Hope it helps!

Upvotes: 1

Related Questions