0

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!

3 Answers 3

1

Simple awk approach:

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

The output:

pr: 10.00    00.00
Sign up to request clarification or add additional context in comments.

3 Comments

Didn't think of that at all. ++
@JamesBrown, yeah, that's why we like AWK, for his simplicity and power ))
\t| = [\t ] or even [[:blank:]] or [[:space:]] but in any case it effectively behaves the same as the default FS and that would replace all tabs with blank chars and the OP specifically said (s)he wants to preserve spacing.
1

To fix your original script would just be:

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

4 Comments

1) your script doesn't even work. Hint: "single quote". 2) the OP wanted to preserve space as well. How that?
1) quote removed, 2) The OP said There's a space between the first and second column, and a tab between second and third column. So the OP has a space between pr: and the first number and then a tab between the 2 pairs of numbers - that is what my script will output.
I'm not stopping him from doing so if he wants. Not sure where you're coming from.
Thanks Ed - Never thought that I could solve the problem in a one-line script! Thank you all for helping with my very first awk script.
0

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

1 Comment

Can I keep the column number instead? The reason is that the value of $20.00 changes sometimes. I'm changing multiple lines in a file, and it's not just one line I'm updating.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.