Search code examples
bashvariablespipeline

Is it possible to set variable in pipeline?


I have a big txt file which I want to edit in pipeline. But on same place in pipeline I want to set number of lines in variable $nol. I just want to see sintax how could I set variable in pipeline like:

  cat ${!#} | tr ' ' '\n'| grep . ; $nol=wc -l | sort | uniq -c ...

That after second pipe is very wrong, but how can I do it in bash?

One of solutions is:

nol=$(cat ${!#} | tr ' ' '\n'| grep . | wc -l)
pipeline all from the start again

but I don't want to do script the same thing twice, bec I have more pipes then here.

I musn't use awk or sed...


Solution

  • You can use a tee and then write it to a file which you use later:

    tempfile="xyz"
    tr ' ' '\n' < "${!#}" | grep '.' | tee > "$tempfile" | sort | uniq -c ...
    nol=$(wc -l "$tempfile")
    

    Or you can use it the other way around:

    nol=$(tr ' ' '\n' < "${!#}" | grep '.' \
      | tee >(sort | uniq -c ... > /dev/tty) | wc -l