Skip to content

Latest commit

 

History

History
108 lines (69 loc) · 2.52 KB

File metadata and controls

108 lines (69 loc) · 2.52 KB

Numeric operations in Linux.

# Numeric Operations in Linux

In Linux, the command-line interface provides powerful tools for performing numeric operations. Whether you need to perform basic arithmetic, more advanced calculations, or manipulate numerical data in files, Linux has the tools to get the job done.

## 1. Basic Arithmetic Operations

### 1.1. Addition

To add two numbers, you can use the `expr` command or the `$(( ))` construct.

```bash
result=$(expr 5 + 3)
echo "5 + 3 equals $result"
# or
result=$((5 + 3))
echo "5 + 3 equals $result"

1.2. Subtraction

Similarly, subtraction can be done using expr or $(( )).

result=$(expr 8 - 2)
echo "8 - 2 equals $result"
# or
result=$((8 - 2))
echo "8 - 2 equals $result"

1.3. Multiplication

Multiplication is achieved using the expr command.

result=$(expr 4 \* 6)
echo "4 * 6 equals $result"

Note: The * needs to be escaped with a backslash (\) to prevent it from being interpreted as a wildcard character.

1.4. Division

Division can also be performed using expr.

result=$(expr 15 / 3)
echo "15 / 3 equals $result"

2. Advanced Arithmetic with bc

For more complex mathematical calculations, the bc command is a powerful tool. It supports floating-point arithmetic and mathematical functions.

2.1. Installation

If not installed, you can install bc using the package manager for your distribution.

# For Debian/Ubuntu
sudo apt-get install bc

# For Red Hat/Fedora
sudo dnf install bc

2.2. Example Usage

echo "scale=2; 7 / 3" | bc
# Outputs: 2.33

The scale parameter sets the number of decimal places.

3. Numeric Manipulation in Files

Linux provides commands to perform numeric operations on data within files.

3.1. awk for Numeric Operations in Files

# Sum the values in the second column of a space-separated file
awk '{sum += $2} END {print sum}' data.txt

3.2. sed for Basic Arithmetic in Files

# Multiply each number in a file by 2
sed 's/[0-9]\+/\n&\n/2;s/\n//;s/\([0-9]\+\)\(.*\)\([0-9]\+\)/\1*\3/' data.txt

Adjust the commands according to your specific needs and file formats.

These are just a few examples of numeric operations in Linux. Depending on your requirements, you may need to combine these tools or explore additional commands for more advanced calculations.