Results 1 to 5 of 5

Thread: grep / xargs question

  1. #1
    Join Date
    Apr 2013
    Beans
    11

    grep / xargs question

    Hello, just trying to understand a subtlety of these commands.

    Code:
    ls | xargs grep "def"
    returns the same thing as
    Code:
    ls | xargs -i grep -H "def" {}
    I'm confused since wouldn't the first command fail as the input is a one-line string? And the first defaults by outputting the filenames whereas usually you need to specifiy -H.

    Thank you

  2. #2
    Join Date
    Feb 2013
    Beans
    Hidden!

    Re: grep / xargs question

    Strictly speaking, the first command is neither string nor necessarily one-line. xargs puts file names as arguments to grep. If there are more arguments than system limits allow, they would be split in several lines. And grep is able to handle multiple file arguments
    Code:
    grep "def" file1 file2 file3 …
    By default, grep prints file names if there more than one file argument even if you don't specify -H.

    BTW, a better way to do the same is
    Code:
    grep 'def' *
    Last edited by schragge; April 8th, 2013 at 09:48 PM.

  3. #3
    Join Date
    Apr 2012
    Beans
    7,256

    Re: grep / xargs question

    also you should be aware that 'ls' isn't safe for this kind of thing, it will break if there are any filenames with spaces:

    Code:
    $ echo "thing1" > file1
    $ echo "thing2" > file2
    $ echo "thing 3" > "file 3"
    $
    $ ls | xargs grep thing
    file1:thing1
    file2:thing2
    grep: file: No such file or directory
    grep: 3: No such file or directory
    whereas the simple shell glob will work:

    Code:
    $ grep thing file*
    file1:thing1
    file2:thing2
    file 3:thing 3

  4. #4
    Join Date
    Apr 2013
    Beans
    11

    Re: grep / xargs question

    Thanks guys. I am aware of the xargs whitespace problem and how to fix it, I was just figuring out how xargs works and now I understand it a little better
    Cheers

  5. #5
    Join Date
    Jul 2007
    Location
    Poland
    Beans
    4,499
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: grep / xargs question

    personally i stay away from xargs. I consider it hackish and not helping much when it comes to learning how shell works.
    in 99% of cases you can do just fine with pure shell features, like for- or while- loop, which while more verbose, offer better readability. Oneliners are overrated
    if your question is answered, mark the thread as [SOLVED]. Thx.
    To post code or command output, use [code] tags.
    Check your bash script here // BashFAQ // BashPitfalls

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •