Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a specific file then pipe to stdout/awk

Tags:

find

bash

stdout

I'm looking for a way to traverse directories recursively to find a specific file, then stop the search and pipe the filename path to an awk function or something similar. I asked a question earlier that was similar, but after testing on machines other than mine it turns out the locate command isn't going to work since not everyone uses it on their system.

Code that I used with locate:

dir="/path/to/destination/";
mkdir "$dir";
locate -l 1 target_file.txt | \
   awk -v dir="$dir" '{printf "cp \"%s\" \"%s\"\n", $1, dir}' | \
   sh
like image 719
Sam Olde Avatar asked Dec 19 '12 08:12

Sam Olde


2 Answers

The find(1) command will do it. To only get one line, use head(1).

dir="/path/to/destination/";
mkdir "$dir";
find /path/location -name target_file.txt |
    head -n 1 |
    awk -v dir="$dir" '{printf "cp \"%s\" \"%s\"\n", $1, dir}' |
    sh
like image 88
kmkaplan Avatar answered Oct 10 '22 17:10

kmkaplan


If you know only one file exists then you can use

find ./ -name "target_file.txt" -exec cp -r {} $dir \;

And if you are not sure, use head to limit 1 and use xargs

find ./ -name "target_file.txt" | head -1 | xargs -I {} cp -r {} $dir/

like image 40
Anil Tallapragada Avatar answered Oct 10 '22 16:10

Anil Tallapragada