user3454156
user3454156

Reputation: 5

awk to replace value in specific column

I have the following line:

pr: 10.00    20.00

I want to replace the third column with "00.00" while preserving tabs and spaces on the line.There's a space between the first and second column, and a tab between second and third column. The following command works EXCEPT it inserts a tab between the first and second column:

awk '$1=="pr:"{OFS="\t"; $3="00.00"}1' mydata.txt > out

How can I keep the space and tabs as they appear in the original line?

Thanks!

Upvotes: 0

Views: 1714

Answers (3)

Ed Morton
Ed Morton

Reputation: 203169

To fix your original script would just be:

awk 'BEGIN{FS=OFS="\t"} $1~/^pr:/{$2="00.00"} 1' mydata.txt > out

Upvotes: 1

James Brown
James Brown

Reputation: 37394

Use sub for it:

$ awk '{sub(/20.00/,"00.00")}1' file
pr: 10.00    00.00

or if it's the last field:

$ awk '{sub(/[^ \t]+$/,"00.00")}1' file
pr: 10.00    00.00

Edit: If you're using GNU awk, splitthe record and store the separators:

$ awk '
{ 
    n=split($0,a,FS,seps)                     # save delim spaces to seps
    a[3]="00.00"                              # changes to a
    for(i=1;i<=n;i++)                         # loop to n
        printf "%s%s",a[i],(i==n?ORS:seps[i]) # print a and seps
}' file
pr: 10.00    00.00

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Simple awk approach:

awk -F'\t| ' '{$NF="00.00"}1' input

The output:

pr: 10.00    00.00

Upvotes: 1

Related Questions