Enter text in a file in a certain column Shell script

1

I have to modify column 5 of a separate text file with : (colon). For the text that the user enters, I already cut column 5 with cut -f5 -d: , but I do not know how to enter the text in that empty space that remains.

The text that the user enters is stored in a variable.

    
asked by Paxa 03.11.2016 в 20:20
source

1 answer

1

Use awk :

awk -v nuevo_valor="NOCHE" 'BEGIN{FS=OFS=":"}{$5=nuevo_valor}1' archivo

How does this work?

  • -v nuevo_valor="NOCHE"
    provides the script with the value to replace the column with.
  • BEGIN{FS=OFS=":"}
    define the field separator; in this case, two points.
  • {$5=nuevo_valor}
    assigns to the 5th field the given value with the variable nuevo_valor .
  • 1 evaluates to True (true) so it executes the default command of awk : {print $0} ; that is, write the current record.

For example:

$ cat archivo
hola:como:estas:esta:mañana:yo:bien
$ awk -v nuevo_valor="NOCHE" 'BEGIN{FS=OFS=":"}{$5=nuevo_valor}1' archivo
hola:como:estas:esta:NOCHE:yo:bien
    
answered by 04.11.2016 в 13:00