Edit file from bash [closed]

1

I ask for help, I must multiply a number within a file, for a fixed value, from bash, the file has the following form, thank you very much.

    
asked by AlexGG 22.07.2018 в 20:20
source

1 answer

1

I can think of something like that.

  • We get that number you want and for that we use a word processor such as cut, awk, etc. So, using the example you put, it would be something like that

    awk 'NR==1{print $2}' < tu_archivo  # Esto es suponiendo que quieres 
                # el campo número 2 y que sólo quieres el primer renglón.
    
    awk '{print $2}' < tu_archivo # En caso de que quieras todos los renglones
    
  • awk has a virtue which is that it can do operations, it's a language, so you could multiply those fields by the value you want.

    awk 'BEGIN{fijo=2}{print $2*fijo}' < tu_archivo  # En caso de que 
                     # quieras multiplicar los valores de todos los renglones.
    
  • Another option that occurs to me (which I would not use once understanding a bit of awk), is with cut and tr.

    valor_fijo=3; tr -s " " < tu_archivo | cut -d " " -f 2 | xargs -I {} echo "{}*$valor_fijo" | bc 
    

    What this line does is create a variable called "fixed_value", then delete the repeated spaces with "tr -s", then, with cut, print field 2 separated by spaces and then print them one by one with xargs adding the string to multiply, that is, it would be of the form "number * fixed_value" and that is passed to the calculator bc.

    Of course I prefer to use awk, but it's fun to mix things up.

    Regarding the last one liner, I assumed that the fields are separated by spaces and not by tabs, that's why, both in tr and cut, I used the "" as a separator.

    In all cases I assumed that you want the values of the second column, if you want you can change this by modifying the number 2 by 1, etc.

        
    answered by 25.07.2018 в 19:47