oaugustopro
oaugustopro

Reputation: 800

Awk command inside pipe inside find

I would like to run the following code:

find 2017_01_04/* -maxdepth 1 -mindepth 1 -type f -exec sh -c\
'file -i $1\ |  awk "{/video|audio/} {print \$1}" ' _ {} \; -print0 | \
while read -d $'\0' -r i
    echo $i
done

The output of file -i command it is:

20170115_202630:                      image/jpeg; charset=binary
20170115_202630.jpg:                  image/jpeg; charset=binary
20171006_204647000_iOS.MOV:           video/quicktime; charset=binary
Ei*foto.jpg:                          image/jpeg; charset=binary
err-organiza_fotos (cópia).log:       text/plain; charset=utf-8
err-organiza_fotos.log:               text/plain; charset=utf-8
err-organiza_fotos (outra cópia).log: text/plain; charset=utf-8

The command above works fine! But when inside the find ... -exec sh -c '... | awk ...' _ {} \; -print0 | while ...; do ...; done doesn't work. Tried everything I know, no success.

file -i * | awk -F ":" '/image|video/ {print $1}'

My goal is to be able to find files and select only ones of a certain type, without have to check for extensions, because, for example there are image files without extensions. And I must use find, because it deals better with files with different names like ./ASD '[]ª\.*. And finally I would like everything in just one command, I know it could be possible using the power of awk and find.

Upvotes: 0

Views: 1300

Answers (2)

chepner
chepner

Reputation: 532053

A find command like that is much simpler as a for loop:

for f in 2017_01_04/*; do
  [ -f "$f" ] || continue
  file -i "$f" | awk '/video|audio/ {print $1}'
done

I assume the extra braces from your awk command were a typo, and the while loop following find didn't seem to serve any immediate purpose. Whatever the body really was (instead of echo "$i") could just as easily be the next member of the pipeline in the body of my for loop.

Upvotes: 1

wef
wef

Reputation: 371

So break it down to something simpler and build on that eg:

find -maxdepth 1 -mindepth 1 -type f -exec file -i {} \; | grep 'video\|image'

which gives (in one of my own directories):

./20190102_104158.jpg: image/jpeg; charset=binary
./20190102_104158-1.jpg: image/jpeg; charset=binary
./20190102_104951-1.jpg: image/jpeg; charset=binary
./20190102_104212.jpg: image/jpeg; charset=binary
./20190102_104158-2.jpg: image/jpeg; charset=binary
./kitchen_sink_set.dwg: image/vnd.dwg; charset=binary
./20190102_104951.jpg: image/jpeg; charset=binary
./20190102_104212-1.jpg: image/jpeg; charset=binary
./20190102_104852.jpg: image/jpeg; charset=binary
./20190102_111832-1.jpg: image/jpeg; charset=binary

Upvotes: 1

Related Questions