Search code examples
sedgrepzshpipingwc

Evaluating a command in bash pipe but return value is wrong


counter=$( grep -n 'ABC' $1 | sed 's/:[a-zA-Z0-9 ]*;//' > $2 | wc -l );

echo $counter; #Output is 0?

the value of the counter should be the output of wc -l right? Why do I find it to be zero? I using zsh. If I execute the command directly I face no problem. Is it something to do with wc that it prints something but return something else? How do I do this correctly.


What I'm doing?

I'm printing line numbers using grep and using sed I'm removing the content of the line and using wc I'm counting the number of lines the output has.


Edit:

Directly on shell fdgs


Ulterior motive:

My ulterior motive is to split a file. To do that I'm identifying some line numbers. So, using grep I'm looking for certain text (as you can see it is SET SCHEMA, in the picture). I don't want the content of the lines just line numbers, so I cut out the lines by identifying the start and end. Using wc -l I'm counting lines.


Solution

  • You can't redirect the output both to a pipe and also to a file at the same time directly. To do that you can use the tee command:

    ... | sed 's/:[a-zA-Z0-9 ]*;//' | tee "$2" | ...