5

Is there a way to run xargs on only the first argument of a line? So if my input is the default output from a grep, like this:

./file1       "matching string"
./file2       "matching 2"

What I want to do is open all of the file names in Vim with something like | xargs vim.

Can I tell xargs to just grab the first word of each line?

I know there are other ways of doing this, including piping to AWK to strip all the extra line garbage, and getting grep to only return the filename - I'm curious whether you can do this with xargs.

1
  • That's why then invented cut? – billc.cn Dec 6 '11 at 23:06
8

As others have stated, generic xargs can't do this alone. Sticking with common Unix tools, you'll need to use the cut command to strip off the extra information before you send it to xargs.

Assuming your input looks like this:

./file1       "matching string"
./file2       "matching 2"

You can use |cut -f 1 -d ' ' | xargs -n 1 vi to run the commands.

  • The cut -f 1 -d ' ' command only sends on what is in column 1 to the output.
  • The xargs -n 1 vi tells xargs to run vi, but only use one file at a time.

It is ok to remove the -n 1 if you want to use a single vi instance to edit all the files (to keep copy/paste buffers across files).

1

You can't do this with xargs itself.

So your options are to make grep output just what you need to pass to xargs, or pipe through cut to strip out what you need in between.

Remember this is the *nix way - to keep each utility as focussed as possible, and use them in combination to achieve results (rather than duplicating functionality in multiple utilities).

1
  • "make grep output just what you need to pass to xargs": That's the -l flag. "grep -l" just outputs the names of the files that match. You can pipe that to xargs. If your filenames might have spaces in them, use "xargs -d \\n". – Randy Orrison Dec 6 '11 at 23:52
1

Using GNU Parallel you can do:

... | grep ... | parallel --colsep ' +' -X --tty vi {1}

It works with emacs, too:

... | grep ... | parallel --colsep ' +' -X --tty emacs {1}

You can install GNU Parallel simply by:

wget http://git.savannah.gnu.org/cgit/parallel.git/plain/src/parallel
chmod 755 parallel

Watch the intro videos to learn more: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

Walk through the tutorial (man parallel_tutorial). You command line with love you for it.

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.