check variable content size in sh script

Teske, Devin Devin.Teske at fisglobal.com
Thu May 16 16:06:52 UTC 2013


On May 16, 2013, at 8:28 AM, Tim Daneliuk wrote:

> On 05/16/2013 10:08 AM, Joe wrote:
>> Hello
>> 
>> Have script that has max size on content in a variable.
>> How to code size less than 51 characters?
>> 
> 
> FOO="Some string you want to check length of"
> FOOLEN=`echo $FOO | wc | awk '{print $3}'`
> 

Uh, without forking to 2 separate programs…

FOOLEN=${#FOO}


> You can then use $FOOLEN in a conditional.
> 


However, if the OP wanted to actually truncate $FOO to 51 characters:


NEWFOO=$( echo "$FOO" | awk -v max=51 '{print substr($0,0,max)}' )


However, if you want to handle the case of $FOO containing newlines (and you want the newline to count toward the max), then this instead would do the trick:


NEWFOO=$( echo "$FOO" | awk -v max=51 '
	{
		len = length($0)
		max -= len
		print substr($0,0,(max > 0 ? len : max + len))
		if ( max < 0 ) exit
		max--
	}' )


$NEWFOO, even if multi-line, will be limited to 51-bytes (adjust max=51 accordingly for other desired-lengths). Newlines are preserved.

Last, but not least, if you want to be able to handle multi-line values but only want to return the first line up-to N bytes (using 51 as the OP used):


NEWFOO=$( echo "$FOO" | awk -v max=51 '{ print substr($0,0,max); exit }' )


If $FOO had multiple lines, $NEWFOO will have only the first line (and it will be truncated to 51 bytes or less).
-- 
Devin

_____________
The information contained in this message is proprietary and/or confidential. If you are not the intended recipient, please: (i) delete the message and all copies; (ii) do not disclose, distribute or use the message in any manner; and (iii) notify the sender immediately. In addition, please be aware that any message addressed to our domain is subject to archiving and review by persons other than the intended recipient. Thank you.


More information about the freebsd-questions mailing list