Hi friends! 🤓 I am on a gnulinux and trying to list all files in the active directory and it’s subdirectories. I then want to pipe the output to “cat”. I want to pipe the output from cat into grep.

Please help! 😅

  • @JTskulk
    link
    English
    1710 months ago

    Bro you can just run find

  • Björn Tantau
    link
    fedilink
    1610 months ago

    Note, you almost never have to use cat. Just leaving it out would have been enough to find your file (although find is still better).

    When you want to find a string in a file it’s also enough to use grep string file instead of cat file | grep string. You can even search through multiple files with grep string file1 file2 file* and grep will tell you in which file the string was found.

      • FuglyDuck
        link
        English
        310 months ago

        for a moment, I thought OP was looking for cat photos or something.

    • @sighofannoyanceOP
      link
      410 months ago

      So I could use something like grep string -R * to find any occurrence of the string in any files in the folder and sub-folders.

      thank you!

      • @[email protected]
        link
        fedilink
        6
        edit-2
        10 months ago

        grep -r string .

        The flag should go before the pattern.

        -r to search recursively, . refers to the current directory.

        Why use . instead of *? Because on it’s own, * will (typically) not match hidden files. See the last paragraph of the ‘Origin’ section of: https://en.m.wikipedia.org/wiki/Glob_(programming). Technically your ls command (lacking the -a) flag would also skip hidden files, but since your comment mentions finding the string in ‘any files,’ I figured hidden files should also be covered (the find commands listed would also find the hidden files).

        EDIT: Should have mentioned that -R is also recursive, but will follow symlinks, where -r will ignore them.

  • Shadow
    link
    fedilink
    1510 months ago

    To answer your og question since it is a valuable tool to know about, xargs.

    ls | xargs cat | grep print

    Should do what you want. Unless your file names have spaces, then you should probably not use this.

  • @surewhynotlem
    link
    410 months ago

    It’s valuable to learn how to do an inline loop

    ls | while read A; do cat $A | grep print; done

    This will read each line of ls into variable A, then it’ll get and grep each one.

  • @visnae
    link
    2
    edit-2
    10 months ago

    grep -r print .

    I.e. Grep on print recursively from . (current directory)

    Or for more advance search find . -name "*.sh" -exec grep -H print {} \;

    I.e find all files with sh extension and run grep on it ({} become the filename). -H to include filename in output.