3

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

$ foo file1.a file2.b file3.a 

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 FAILURE 

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.

3
  • 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. Commented Jun 6, 2016 at 20:58
  • how is it even possible to know about something relatively obscure like xargs but not grep or sed? Commented Jun 7, 2016 at 4:28
  • @cas Completely forgot that grep would view the standard input as a file rather than checking each file's contents. Commented Jun 7, 2016 at 10:26

1 Answer 1

9

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

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

4
  • Hmm, wouldn't grep \\.a$ be better? Oh, I see someone else got there first Commented Jun 6, 2016 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 Commented Jun 7, 2016 at 4:26
  • @cas - Thank you for the suggestions. I have edited the answer. Commented Jun 7, 2016 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. Commented Jun 7, 2016 at 23:46

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.