2

I have this two step bash command:

L=`wc -l testfile | cut -d' ' -f1`
myprogram testfile $L testfile.out

Long story short, myprogram needs the line count as an input.

I want to combine this into one line.

This does not work because using redirect | to - passes stdout stream as a file, not a string.

wc -l testfile | cut -d' ' -f1 | myprogram testfile - testfile.out

Is there a way to combine this into one line?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
BAMF4bacon
  • 523
  • 1
  • 7
  • 21

1 Answers1

5

Use process substitution:

myprogram testfile $(wc -l < testfile) testfile.out
                   ^^^^^^^^^^^^^^^^^^^

This way, wc -l < testfile is evaluated together with the call of the program and you have both commands combined.

Note wc -l < file returns you just the number, so you don't have to do cut or any other thing to clean the output.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Or myprogram testfile """ wc -l < testfile """ testfile.out with oblic qote instead of """"" – yonutix Apr 08 '15 at 14:54
  • @CosminMihai yep! Only that in general `$()` is preferred --> [Why is $(...) preferred over `...` (backticks)?](http://mywiki.wooledge.org/BashFAQ/082). – fedorqui Apr 08 '15 at 14:56
  • @CosminMihai in many cases they are the same, it just hurts if you want to nest them. If you are doing ` it is not possible! (And also, see how complicated it is to write them in comments :D) – fedorqui Apr 08 '15 at 14:59