Getting length of output in shell

Hi all,

I need a command in shell, which will return the length of the output as well as the actual output.

So, for example, if I run "date" command, it returns something like:

Wed Nov 24 22:46:53 IST 2010

What I need is, some manipulation to this, so that I get output like:

Wed Nov 24 22:46:53 IST 2010

Here 29 is the length of the output string (Wed Nov 24 22:46:53 IST 2010).

I can do it this way:

$date | wc -c ; date

But this runs "date" command twice, which I want to avoid. I tried to use "tee" without success. Is there any way to do this?
LVL 37
Harisha M GAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

woolmilkporcConnect With a Mentor Commented:
Now I copied and pasted your version instead of mine. Sorry!

date | awk '{print length+1 "\n" $0}'

woolmilkporcConnect With a Mentor Commented:

date | awk '{printf "%d\n%s", length, $0}'

or simpler, all output in one line:

date | awk '{print length, $0}'

woolmilkporcConnect With a Mentor Commented:
If you don't like "printf" and need the output in two lines nonetheless:

date | awk '{print length "\n" $0}'

Btw. awk gives length 28, because it doesn't count the terminating linefeed.
Build your data science skills into a career

Are you ready to take your data science career to the next step, or break into data science? With Springboard’s Data Science Career Track, you’ll master data science topics, have personalized career guidance, weekly calls with a data science expert, and a job guarantee.

Harisha M GAuthor Commented:
Thanks woolmilkporc. Adding one shouldn't be a problem.

Is there any way to get it in two different lines?

I tried

date | awk '{print length"\n",$0}'

But it is prepending one extra space in second line:

 Wed Nov 24 23:04:17 IST 2010
See the first solution in the first post and the one in the second post.
woolmilkporcConnect With a Mentor Commented:
"comma" between output field specifications stands for "insert a space" in awk, whereas a space stands for "concatenate".
Just for fun - a silly version with "tee":

date | tee xxx.$$ | wc -c | tr -d " "; cat xxx.$$; rm xxx.$$

Adding one should not be a problem, indeed:

date | awk '{print length+1"\n",$0}'
Here's an alternative solution with only one fork

echo -e "${#d}\n$d"
Harisha M GAuthor Commented:
TinTin, that's around 45% faster!!

I can't assign points to you now, but thank you so much!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.