Retrieving values from a line in text file

Hi,
I am new to Unix/ksh script and will like to check how do I retrieve just the count of '258' in the last line in a text file ?
There will be this "TRL" appended with number of count at the last line in a text file .

TRL0000000258
var=`grep 'TRL' $HOME/folder/test.txt | wc -l`

How do i substr and get the last 10 values into a variable ?

Appreicate anyone who can help me . Thank You.

Can you post the input file?

---------- Post updated at 05:54 AM ---------- Previous update was at 05:38 AM ----------

I think you are excepting this one...

 echo "TRL44440000000258"|awk '{ print substr( $1, length($1) - 9, length($1) ) }'  

Try:

var=$(tail -1 infile)
var=${var#TRL}
var=$(sed -n '$s/TRL//p' infile)

Input file :

AAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCC
TRL0000000258

command :

awk ' /^TRL/ {sub(/TRL/, "") ; print } ' file

output :

0000000258
awk '/^TRL/{sub(/TRL0+/,"")}1' test.txt

Yet another way...

echo TRL0000000258 | awk '{gsub("[^0-9]", "");print $0+0}'

try also (using Scrutinizer's sed example) for eliminating leading non valid chars for numbers:

var=$(sed -n '$s/^[^1-9]*//p' infile)

Hi Fundix,

Input File :

AAAAAAAAAAAAAAAA
BBBBBBBBBBBBBBBB
CCCCCCCCCCCCCCCC
TRL0000000258

When I try to code using

awk ' /^TRL/ {sub(/TRL/, "") ; print } ' $src_file

, it will prompt me for the below error :

awk:syntax error near line 1
awk:illegal statement near line 1.

Thanks everyone for your help !

On Solaris use /usr/xpg4/bin/awk rather than awk

Hi Scrutinizer ,
Thanks .
Is it possible for me to eliminate leading non valid chars for numbers?

Example :

0000000002

To get 2 as the variable instead.

Thanks

Hi, try forcing a numerical context by using print $0+0 instead of print (which is equivalent to print $0 ), thus losing the leading zeroes

awk ' /^TRL/ {sub(/TRL/, "") ; print $0+0 } ' file

Or remove the leading zeroes as part of the substitution:

awk 'sub(/^TRL0*/,x)' file
sed -n '$s/^TRL0*//p' file

Hi Scrutinizer,
Is it possible for me to assign the value to a variable instead of just printing out on screen ?

var=awk 'sub(/^TRL0*/,x)' file
echo $var

Sorry. I am not that familar with using awk and ksh unix. Thank You.

Use:

var=$(awk 'sub(/^TRL0*/,x)' file)
1 Like