简体   繁体   中英

Bash, how can I apply one arithmetic expression to every line?

I have two scripts, A and B.

I want to execute them and read respectively two values. V and VALS.

V is just a floating point number, let's say 0.5

VALS has the following format:

1 10
2 20
3 60
4 45

and so on.

What I'm trying to do is to get a new variable where the second column of VALS (10, 20, ...) is divided by V.

As I understand this can be implemented with a mix of xargs and cut but I'm not really familiar with these tools.

#!/bin/bash

V=`./A`
VALS=`./B`
RESULT=#magic happens

The final result with the previous data should be:

1 20
2 40
3 120
4 90

Bash's builtin arithmetic expansion only works for integers. You can use awk for data extraction and floating point numbers.

V=`./A`
# No VALS needed
RESULT=($(./B | awk "{print \$2 / $V"}))

Note the escaped dollar sign in \\$2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM