ziulfer
ziulfer

Reputation: 1369

change a specific line of a file using awk

I have a file which I want to modify in a specific line. I had use this:

#!/bin/bash/
cp /dir1/dir2/FILE_to_be_modified . ;
var ="$1 $1 $1";
awk -v li=4 -v new="$var" '{
        if (NR==li) {
                  print new;
        } else {
                 print $O;
        }
}' FILE_to_be_modified>>new_FILE

with this I could modified line 4 of FILE_to_be_modified but always with patterns like 9 9 9 12 12 12, now I'd like something like 9 9 11 or 12 12 14. I've tried silly thinks like changing var to $1 $1 $1+2. should I use bc?

Upvotes: 0

Views: 3061

Answers (3)

glenn jackman
glenn jackman

Reputation: 247002

Alternatively, you could hand off the arithmetic to awk

#!/bin/sh
awk -v li=4 -v val="$1" '
    NR==li {print val, val, val+2; next}
    {print}
' /dir1/dir2/FILE_to_be_modified >> ./new_FILE

Upvotes: 0

brice
brice

Reputation: 25039

Bash arithmetic:

var = "$1 $1 $(($1 + 2))"

Have a look at the docs and the tutorial.

Upvotes: 3

Michał Kosmulski
Michał Kosmulski

Reputation: 10020

When you write var ="$1 $1 $1", you let bash, not awk, expand the variables. $1 accidentally has a meaning both in awk and in bash. So what you do now is replace the line with 3 occurrences of the first argument passed to your script. By changing it to e.g. var ="$1 $2 $3" you will use the 3 first parameters passed to your script. If, on the other hand, your goal is to replace the line with the values of first field as seen by awk, use a single quote: var ='$1 $1 $1'. This way bash won't expand it, only awk will and if you change it to var ='$1 $2 $3' you will be replacing the line with the first 3 fields of original value (as seen by awk).

Upvotes: 1

Related Questions