BASH: how to perform arithmetic on numbers in a pipe

前端 未结 10 1971
忘掉有多难
忘掉有多难 2021-01-18 08:12

I am getting a stream of numbers in a pipe, and would like to perform some operations before passing them on to the next section, but I\'m a little lost about how I would go

相关标签:
10条回答
  • 2021-01-18 08:25
    echo 1 2 3 4 5 | xargs -n 1 bash -c 'echo $(($1*$1))' args 
    
    0 讨论(0)
  • 2021-01-18 08:26

    xargs, xargs, xargs

    echo 1 2 3 4 5 | xargs -n1 echo | xargs -I NUMBER expr NUMBER \* NUMBER | xargs
    

    Or, go parallel:

    squareit () { expr $1 \* $1; }
    export -f squareit
    echo 1 2 3 4 5 | xargs -n1 | parallel --gnu squareit | xargs
    

    Which would be way simpler if you passed your pipe as a standard set of args:

    parallel --gnu "expr {} \* {}" ::: $(echo 1 2 3 4 5) | xargs
    

    Or even:

    parallel --gnu "expr {} \* {}" ::: 1 2 3 4 5 | xargs
    

    Really worth taking a look at the examples in the doc: https://www.gnu.org/software/parallel/man.html

    0 讨论(0)
  • 2021-01-18 08:34
    echo 1 2 3 4 5|{
      read line; 
      for i in $line;
      do
        echo -n "$((i * i)) "; 
      done; 
      echo
    }
    

    The {} creates a grouping. You could instead create a script for that.

    0 讨论(0)
  • 2021-01-18 08:38

    Or you can pipe to expression to bc:

    echo "1 2 3 4 5" | (
      read line; 
      for i in $line;
      do
        echo $i^2 | bc; 
      done; 
      echo
    )
    
    0 讨论(0)
提交回复
热议问题