Extracting value from a flat file using shell script

871 views Asked by At

I'm trying to extract the value present between brackets in the last row of a flat file e.g. " last_line (4) ". This is the last line and I want to extract 4 and store it in a variable. I have extracted the last row using tail command but now I am unable to extract the value between the brackets.

Kindly help.

4

There are 4 answers

1
Fredrik Pihl On

Using awk:

$ cat input
first line
2nd line
last line (4) with some data

$ awk -F'[()]' 'END{print $2}' input
4
0
Kent On

sed:

sed -n '${s/.*(//;s/).*//;p}' file
0
David C. Rankin On
l=$(tail -n1 filename); tmp=${l##*(}; tmp=${tmp%)*}; printf "tmp: %s\n" $tmp

Output

tmp: 4

Written in script format, you are using substring removal to trim everything up to the first ( and everything after the last ) from the last line, leaving only 4:

l=$(tail -n1 filename)    ## get the last line
tmp=${l##*(}              ## trim to ( from left
tmp=${tmp%)*}             ## trim to ) from right
printf "tmp: %s\n" $tmp
0
Grv On

U can use this script.

In this script i saved the last line in a tmp file and at last removed it. the number between the brackets() is in variable WORD

 #!/bin/ksh

if test "${DEBUG}" = "Y"
then

   set -vx

fi

tail -1 input>>tmp


WORD=`sed -n 's/.*(//;s/).*//;p' tmp`

echo $WORD

rm tmp