I've got a command foo that outputs a list of filenames:

$ foo

And a command bar that accepts the names of .a files as arguments and does some processing:

$ bar file1.a file3.a
Great success!
$ bar file2.b

I'd like to combine the two with a pipe like foo | xargs bar, but I need to filter out all filenames that don't end in .a. How can I do this? Ideally I want something simple I can stick between the two commands in a pipe, like foo | filter-lines ".a" | xargs bar.

  • 5
    You should read up on the 'text processing' tag, and learn some or all of the following tools: grep, sed, awk; and also cut, paste, join. For the postgraduate text-processing tool you can learn Perl, but in 99% of cases you can accomplish everything you want with a simple grep or sed one-liner. – Wildcard Jun 6 '16 at 20:58
  • how is it even possible to know about something relatively obscure like xargs but not grep or sed? – cas Jun 7 '16 at 4:28
  • @cas Completely forgot that grep would view the standard input as a file rather than checking each file's contents. – Jack Jun 7 '16 at 10:26

You can use grep to grab all files within foo that end with .a.

foo | grep "\.a$" | xargs -d'\n' -r bar

  • Hmm, wouldn't grep \\.a$ be better? Oh, I see someone else got there first – infixed Jun 6 '16 at 20:59
  • +1. you should use xargs -d'\n' bar for safety, in case any filenames have spaces or other annoying characters in them. If you're using GNU xargs, you should also use -r or --no-run-if-empty so that xargs doesn't run bar if the input is empty: xargs -d'\n' -r bar – cas Jun 7 '16 at 4:26
  • @cas - Thank you for the suggestions. I have edited the answer. – Peschke Jun 7 '16 at 4:44
  • if foo produced NUL-separated output, you could use xargs -0r (and grep -z) and it would work even with filenames that have embedded newlines...but you have to work with what you get. – cas Jun 7 '16 at 23:46

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.