Search code examples
bashsedgrepcut

Bash: grep command for divide a line between ":" and showing the third part


The script read a file by argument.

Then the script will ask for the two cities, origin_city and destiny_city from which we want to get their distance.

Once introduced, it will search if there is any line origin_city:destiny_city:distance in the file of the distances

If found, it will show the distance, if not, it will report it.

Example:

Show distance between cities

Intro origin_city: Barcelona (we input it / read it)

Intro destiny_city: Madrid (we input it / read it) 

Distance: 623 Km

The file format is:

Barcelona:Valencia:350
Barcelona:Madrid:623
Valencia:Zaragoza:308
Madrid:Lugo:505
Barcelona:Sevilla:995

So, I know I need to use grep here and probably sed and cut, but don't know how, so I'm asking for your help. I have this but don't work:

grep origen:desti
if [ "$origen" == $(cut -d":" -f1) ]
then
    echo "1"
else    
    echo "0"
fi

How can I solve this?


Solution

  • With :

    origin=Barcelona
    destination=Madrid
    distance=$(awk -F: -vf=$origin -vt=$destination '$1==f && $2==t{print $3}' file)
    if [[ $distance ]]; then
        echo "$origin => $destination: $distance"
    else
        echo >&2 "no match"
    fi
    

    Output

    623