Search code examples
linuxstringgreppattern-matchingxxd

Searching for a specifc given hex string in multiple images on Linux


I am doing some research on image processing and I wanted to know if its possible to search for a specific hex string/byte array in various images. It would be great if it gives me a list of images that has that specific string. Basically what grep -r "" does. For some reason grep doesn't do the job. I am not familiar with strings. I did had a look at "man strings" but it didn't help much. Anyways, I would like to look for a specific hex string say "0002131230443" (or even specific byte array i.e. base64 string) in several images in the same folder. Any help would be highly appreciated.

I found this code which exactly does what I want using xxd and grep. Please find the command below: xxd -p /your/file | tr -d '\n' | grep -c '22081b00081f091d2733170d123f3114'

FYI: It'll return 1 if the content matches, 0 else.

xxd -p converts the file to plain hex dump, tr -d '\n' removes the newlines added by xxd, and grep -c counts the number of lines matched.

Does anyone know how to run the code above in a specific directory using bash script. I have around 400 images and I want it to return only 400 (i.e. a string matching count) if all the 400 images have that particular string. I found this script code below but it runs the same code over and over for 400 times returning either 0 or 1 each time:

#!/bin/bash

FILES=/FILEPATH/*
for f in $FILES
do
   echo "PROCESSING $f FILES"
   echo "-------------------"
   XXD -u $f | grep ABCD
   echo "-------------------"
done

Thanks guys.

Plasma33


Solution

  • With GNU grep:

    #!/bin/bash
    
    files=/FILEPATH/*
    for f in $files
    do
      grep -m 1 -P '\x22\x08\x1b\x00' < "$f"
    done | wc -l