BASH: how to perform arithmetic on numbers in a pipe

前端 未结 10 1976
忘掉有多难
忘掉有多难 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:21

    Using awk is another solution, which also works with floats

    echo "1 2 3 4 5" | xargs -n1 | awk '{print $1^2}' | xargs
    

    or use a loop

    for x in 1 2 3 4 5; do echo $((x**2)); done | xargs
    for x in $(echo "1 2 3 4 5"); do echo $x^2 | bc; done | xargs # alternative solution
    for x in $(seq 5); do python -c "print($x**2)"; done | xargs  # alternative solution but slower than the above
    # or make it neat by defining a function to do basic math in bash, e.g.:
    calc() { awk "BEGIN{print $*}"; } 
    for x in $(seq 5); do calc $x^2; done | xargs
    

提交回复
热议问题