Home > Net >  Extracting Number From a File
Extracting Number From a File

Time:04-26

I'm trying to write a script (with bash) that looks for a word (for example "SOME(X) WORD:") and prints the rest of the line which is effectively some numbers with "-" in front. To clarify, an example line that I'm looking for in a file is;

        SOME(X) WORD:       -1.0475392439   ANOTHER.W=  -0.0590214433

I want to extract the number after "SOME(X) WORD:", so "-1.0475392439" for this example. I have a similar script to this which extracts the number from the following line (both lines are from the same input file)

 A-DESIRED RESULT W(   WORD) =       -9.68765465413

And the script for this is,

local output="$1"
local ext="log"
local word="W(   WORD)"

cd $dir

find "${output}" -type f -name "*.${ext}" -exec awk -v ptn="${word}" 'index($0,ptn) {print $NF,FILENAME}' {}  

But when I change the local word variable from "W( WORD)" to "SOME(X) WORD", it captures the "-0.0590214433" instead of "-1.0475392439" meaning it takes the last number in line. How can I find a solution to this? Thanks in advance!

CodePudding user response:

As you have seen, print $NF outputs the last field of the line. Please modify the find line as:

find "${output}" -type f -name "*.${ext}" -exec awk -v ptn="${word}" 'index($0, ptn) {if (match($0, /-[0-9] \.[0-9] /)) print substr($0, RSTART, RLENGTH), FILENAME}' {}  

Then it will output the first number in the line.
Please note it assumes the number always starts with the - sign.

  • Related