Home > Mobile >  bin bash script that takes the name of such a file
bin bash script that takes the name of such a file

Time:04-19

Each line always consists of two columns.

In each column I have two strings separated by a space.

How I can write a script that takes the name of such a file as the first argument and calculates the sum on subsequent pairs of numbers read from our file.

I have to display information about errors - why the given line can not be processed, if such a situation occurred

So for example I have:

100 300
20 10
11 0 
55
11 11a11
333 3

CodePudding user response:

Here is an example implementation:

#!/bin/bash

while read line; do
    if [[ ! -z ${line} ]]; then
        echo "Processing line: \"${line}\":"

        v1=$(awk -F ' ' '{ print $1 }' <<< ${line})
        v2=$(awk -F ' ' '{ print $2 }' <<< ${line})

        if [ -z "${v1}" ] || [ -z "${v2}" ]; then
            echo " > Invalid provided value(s)!"
        else
            result=$(expr ${v1}   ${v2})

            if [[ ! -z ${result} ]]; then
                echo " > Result of ${v1}   ${v2} is ${result}."
            else
                echo " > Sum failed!"
            fi
        fi
    fi
done < {{YOUR_INPUT_FILE}}

Please, remember to replace the {{YOUR_INPUT_FILE}} variable.

CodePudding user response:

how do you want "11a11" to be calculated as ? Is it hex ?

  • Related