Search code examples
unixfindxargs

xargs Format output while cating files


I am combining xargs with find and have a bunch of files which I want to cat

find something
A
B
C

Now I am doing

find something | xargs cat

I want to put Echo the name of the file and some display message between the cat outputs. I tried -t option but it displays all the commands on top. Is xargs the way to go here? If so how should I proceed?


Solution

  • Try:

    find . -name something -exec echo "File:" {} \; -exec cat {} \;
    

    This is safe even for files whose names contain spaces, newlines, or other difficult characters.

    Example

    Let's have these test files:

    $ cat A
    1
    2
    $ cat B
    3
    4
    $ cat C
    5
    6
    

    The command output looks like:

    $ find . -name '[ABC]'  -exec echo "File:" {} \; -exec cat {} \;
    File: ./B
    3
    4
    File: ./C
    5
    6
    File: ./A
    1
    2
    

    How it works

    • find . -name something

      This starts the find command with whatever options you like

    • -exec echo "File:" {} \;

      For every file found, this prints File: followed by its name.

    • -exec cat {} \;

      This prints the contents of the file.