2

Im trying to search all files within a directory by name and outputting the files' content onto the shell.

Currently I'm only getting a list of files

find -name '.htaccess' -type f


./dir1/.htaccess
./dir23/folder/.htaccess
...

But how can I output the content of each file instead. Thought of something like piping the filename to the cat-command.

6

Use cat within the -exec predicate of find:

find -name '.htaccess' -type f -exec cat {} +

This will output the contents of the files, one after another.

  • I was wondering if it's even possible to output the filename right before each content – pbaldauf Jan 19 '17 at 7:28
  • 1
    @pbaldauf Do: find . -type f -name file.txt -exec sh -c 'printf "%s\n%s\n\n" "$1" "$(cat -- "$1")"' _ {} \; – heemayl Jan 19 '17 at 8:03
2

See the manual page for find (man find).

-exec utility [argument ...] ;
         True if the program named utility returns a zero value as its exit
status. Optional arguments may be passed to the utility. The expression must be
terminated by a semicolon (``;'').  If you invoke find from a shell you may need
to quote the semicolon if the shell would otherwise treat it as a control
operator. If the string ``{}'' appears anywhere in the utility name or the
arguments it is replaced by the pathname of the current file.  Utility will be
executed from the directory from which find was executed. Utility and arguments
are not subject to the further expansion of shell patterns and constructs.

-exec utility [argument ...] {} +
         Same as -exec, except that ``{}'' is replaced with as
many pathnames as possible for each invocation of utility.  This behaviour is
similar to that of xargs(1).

So, just tack on the -exec switch.

find -type f -name '.htaccess' -exec cat {} +
1

You probably want to use the -exec option of find.

find -name some_pattern -type f -exec cat {} +

Moreover, if all of them are plain text and you want to view them one by one, replace cat with less (or view from vim)

find -name some_pattern -type f -exec less {} +

To view & edit, use vim or emacs or gedit (at your own option)

find -name some_pattern -type f -exec vim {} +

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.