0

I have a data file say file1.txt, I want to match a pattern ("best-fit point:" or "best-fit") then print the last column of that line.

File1.txt

best-fit point:  0.0000  0.0000  0.0000   x coordinate   0.0000
best-fit point: -0.4330 -0.2500  0.0884   x coordinate   0.5078
best-fit point:  0.8660  0.5000 -0.1768   x coordinate   2.0310
best-fit point: -0.4330  0.2500  0.1768   x coordinate   3.4003
best-fit point:  0.8660  1.0000 -0.0884   x coordinate   4.9236
best-fit point:  0.4330  0.7500  0.0000   x coordinate   5.4313
best-fit point:  0.8660 -0.5000 -0.3536   x coordinate   6.8006
best-fit point:  0.0000  0.0000  0.2652   x coordinate   7.9766
best-fit point:  1.2990  0.7500  0.0000   x coordinate   9.4998
best-fit point:  0.8660  0.5000  0.0884   x coordinate  10.0076
best-fit point:  1.2990 -0.7500 -0.2652   x coordinate  11.3769
best-fit point:  0.8660 -1.0000 -0.1768   x coordinate  11.8846
best-fit point:  0.0000  0.0000 -0.5303   x coordinate  13.2539

Output

 0.0000
 0.5078
 2.0310
 3.4003
 4.9236
 5.4313
 6.8006
 7.9766
 9.4998
10.0076
11.3769
11.8846
13.2539

My Solution and its problem

awk '/best-fit point:/{i==0 ; i++; print "K"i"="$8}' file-1.txt

This awk command is successfully working if there is no negative data in any column. Is there any other way to print the last column after the pattern match?

Thanks in advance!

0
4

If your input’s last column is always separated from the previous column, you can ask AWK to output the last column by referring to the number of fields:

awk '/best-fit point:/ { printf "%7.4f\n", $NF }'

will produce the output shown in your question.

However it appears that your input is really using fixed-width columns. If you’re using GNU AWK, you can use FIELDWIDTHS to specify the columns:

awk -vFIELDWIDTHS="21 7 7 7 16 8" '/best-fit point:/ { printf "%7.4f\n", $6 }'
0
2

With grep:

grep 'best-fit' file.txt | grep -Eo ' .[^ ]*$'

Selecting only lines with "best-fit", then reducing it to "[space]string[line end]".

If your format is as fixed as in your input, you may also just cut a character range

grep 'best-fit' file.txt | cut -c60-
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.