0

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.

Johan
  • 8,068
  • 1
  • 33
  • 46
daniyal.bashir
  • 88
  • 4
  • 14

4 Answers4

1

Using awk:

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

$ awk -F'[()]' 'END{print $2}' input
4
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
  • Right approach so `+1` but the last record read is only saved in the `END` section in some awks, to be portable you need to use `awk -F'[()]' '{s=$2} END{print s}' input`. – Ed Morton Aug 12 '15 at 17:03
1
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
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
0

sed:

sed -n '${s/.*(//;s/).*//;p}' file
Kent
  • 189,393
  • 32
  • 233
  • 301
0

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
Ashish Kakkad
  • 23,586
  • 12
  • 103
  • 136
Grv
  • 273
  • 3
  • 14