Find files and echo content on shell

7,742

Solution 1

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.

Solution 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 {} +

Solution 3

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 {} +
Share:
7,742

Related videos on Youtube

pbaldauf
Author by

pbaldauf

Updated on September 18, 2022

Comments

  • pbaldauf
    pbaldauf almost 2 years

    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.

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