I can’t change the value I want from a file through Shellscript

Asked

Viewed 41 times

0

88020:Maria Aguiar:EIB2:914256321:[email protected]:carro:Mercedes:1414-TX-13:13:14:4
83605:Tiago Domingues:ETA4:934442913:[email protected]:carro:BMW:14-TD-16:1:130:200

I have this code in a file, name condutores.txt. And in the script I wanted to change the ninth column by a value I want for example.

And I’ve tried this:

Numero9=$(cat condutores.txt | awk -F ':' '{print $9}' | tail -n +$1 | head -1)

NovoNumero9=$(( $Numero9+ 1 ))

sed -i 's/'"$Numero9"'/'"$NovoNumero9"'/' condutores.txt

But it changes me every place along the line where the $Numero9 and I wanted it to change only in the ninth column, the columns being divided by ":".

  • That’s shellscript, not javascript rs...

2 answers

0


I advise you to do this line by line, as follows:

# verifica o número de linhas que o arquivo tem
linhas=$(wc -l file | awk '{print $1}')
# pega o conteúdo do arquivo e coloca na variável
file=$(cat file)
# faz um laço for para subistituir linha a linha
for (( i = 1; i <= $linhas; i++ )); do
    # pega o conteúdo da linha em questão
    linha=$(sed -n $i'p' <<<"$file")
    # pega o valor da coluna em questão, da linha $i
    value=$(awk -F: '{print $9}' <<<$linha)
    # novo falor para ser substituído
    n_value=$[value + 1]
    # faz a substituição dos valores
    n_linha=${linha/:$value:/:$n_value:}
    # faz a substituição da linha no arquivo, com os novos valores
    file=${file/$linha/$n_linha}
    # escreve no arquivo
    echo "$file" > file
done

This script overwrites the original file, for testing it is advised to create a new file by changing the last line of the for

echo "$file" > file

0

Can use

awk -F: -v OFS=':' '$9 == "13" { $9 = "888" }1'  arquivo

if you want to write to a new file, use > newfile at the end of the command

Browser other questions tagged

You are not signed in. Login or sign up in order to post.