icedTea
icedTea

Reputation: 495

shell script to search for a file and then echo contents of file

I am trying to to create a shell script to echo the contents of a file that I am not sure where to find it.

I thought it would be something like:

$echo | ls /* | grep file.xml

where my file could be in some unknown subfolder so I am trying to search for it's path with grep.

Any help on correct syntax would be greatly appreciated!

Upvotes: 0

Views: 13929

Answers (3)

ruakh
ruakh

Reputation: 183341

You can use find:

find / -name file.xml -exec cat '{}' ';'

/ says to look in / and its subdirectories; -name file.xml says to find files named file.xml; and -exec cat '{}' ';' says to run, e.g., cat /path/to/file.xml for each of those files, which prints out their contents.

Upvotes: 5

icyrock.com
icyrock.com

Reputation: 28608

Try this:

grep -lr "alice in wonderland" *

This will list all the files that contain text alice in wonderland. If you want to display the contents of each, do this:

grep -lr "alice in wonderland" *|while read filename; do
  echo ---- Contents of: "$filename"
  cat "$filename"
done

Upvotes: 0

ABS
ABS

Reputation: 2162

I think you want to cat the file. Note that it will print all files if there are multiple matches. You may get permission errors you need to filter if you aren't sufficiently privileged. To avoid, only run on directories to which you have rights, execute with escalated privileges or use grep to remove them. Try:

cat `find / -name file.xml`

Upvotes: 0

Related Questions