0

I have this file called viagens.txt:

2018-10-01:88020:88013:6:4.2
2018-10-01:88020:88014:8:3.8

I want to create a script that, in each line, checks the second column (in this case, in both cases it would return "88020").

However, right now, I can't filter it to get that number on the 2nd column. I have this code:

#!/bin/bash
fich=viagens.txt
condutores=condutores.txt
if [ -f $fich ];then
    for f in $(cat $fich); do
        condutor=$(cut -f2 $f)
        echo $condutor
    done
else
    echo "Ficheiro nao existe"
fi

I also tried

#!/bin/bash
fich=viagens.txt
condutores=condutores.txt
if [ -f $fich ];then
    for f in $(cat $fich); do
        condutor=$(cat $f | cut -d' ' -f2)
        echo $condutor
    done
else
    echo "Ficheiro nao existe"
fi

What am I doing wrong?

Thanks in advance.

1

In both of your scripts, you use cut on a file whose name is read from the viagens.txt file. You ought to get a No such file or directory error from both scripts (remember to always include any errors in the question).

Instead:

#!/bin/bash

fich=viagens.txt

if [ ! -f "$fich" ]; then
    echo "Ficheiro nao existe" >&2
    exit 1
fi

cut -d : -f 2 <"$fich" |
while read data; do
    printf 'Data read: %s\n' "$data"
done

The cut -d : -f 2 will return the second :-delimited field from the input to cut.

Or, if you just want to output the column:

#!/bin/bash

fich=viagens.txt

if [ ! -f "$fich" ]; then
    echo "Ficheiro nao existe" >&2
    exit 1
fi

cut -d : -f 2 <"$fich"
0

How about - not withstanding a prior check for file's existence - reading the file's lines into an array, with IFS set to :, and print the second element?

IFS=:
while read -a TARR; do echo ${TARR[1]}; done < viagens.txt
88020
88020

Don't forget to set IFS back to its original value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.