Link to home
Create AccountLog in
Avatar of new_perl_user
new_perl_user

asked on

Length of Variable in Shell

Hi,
I am grepping Data from log file and assigning it to a Variable. Now I need to know length or count of that Variable. Can anyone let me know how??

I mentioned Count because I am grepping the filenames into Var . For example when we print that Variable data would be:

FILE1
FILE2
FILE3..

Avatar of Gerwin Jansen
Gerwin Jansen
Flag of Netherlands image

There is a few ways you can do this. Let's say the variable that contains your grepped data is called result. You can determine the length of result like this:

user@VMMINT01 ~/tmp $ result="this is the result"
user@VMMINT01 ~/tmp $ echo $result
this is the result
user@VMMINT01 ~/tmp $ expr length "$result"
18
user@VMMINT01 ~/tmp $ echo ${#result}
18

Open in new window

Or assign the lengt to a variable:

user@VMMINT01 ~/tmp $ result_len=`expr length "$result"`
user@VMMINT01 ~/tmp $ echo $result_len
18

Open in new window

Avatar of new_perl_user
new_perl_user

ASKER

I tried the above suggestion, but it is printing the wrong count/length.
 There are only 3 filenames in the file but it is showing 5.
Are you working in Perl or some shell scripting language like KSH, SH, CSH?

For most scripting languages you could do something like:

$length=`echo $var | wc -l`
(count lines)

$length=`echo $var | wc -c`
(count characters)
Hi

Below is the script I am using.. I want to get the count into a variable so that I can populate that into an email subject showing the count of file names

#!/bin/bash

 i=$(egrep -v "^$|[/]$" /usr/home/Test/Files/test_`date +%Y%m%d`_mhl.txt);
echo "$i"\n;
$length ='echo $i|wc -l';

Try it this way:
 
i=$(egrep -v "^$|[/]$" /usr/home/Test/Files/test_`date +%Y%m%d`_mhl.txt);
echo "$i";
length=$(echo $i|wc -l);
echo $length;

Open in new window

Above one is giving the count of file it is grepping instead of count of Filenames within the file.

So right now it is grepping "1" file to read  so the output is 1.
ASKER CERTIFIED SOLUTION
Avatar of Anacreo
Anacreo

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer