check variable content size in sh script
Teske, Devin
Devin.Teske at fisglobal.com
Thu May 16 16:48:28 UTC 2013
On May 16, 2013, at 9:27 AM, Teske, Devin wrote:
On May 16, 2013, at 9:06 AM, Teske, Devin wrote:
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--
}' )
For fun, I decided to expand on the solution I provided immediately above… turning it into a function that you might be a little more familiar with:
snprintf()
{
local __var_to_set="$1" __size="$2"
shift 2 # var_to_set/size
eval "$__var_to_set"=\$\( printf \"\$@\" \| awk -v max=\"\$__size\" \''
{
len = length($0)
max -= len
print substr($0,0,(max > 0 ? len : max + len))
if ( max < 0 ) exit
max--
}'\' \)
}
Example usage:
FOO=$( printf "abc\n123\n" )
snprintf NEWFOO 6 "%s" "$FOO"
echo "NEWFOO=[$NEWFOO] len=[${#NEWFOO}]"
Produces:
NEWFOO=[abc
12] len=[6]
Hopefully this should help some folks.
I figured I'd help as many folks as I can…
http://svnweb.freebsd.org/base?view=revision&revision=250701
Added it to my string processing library. Lots of other useful functions in there.
--
Cheers,
Devin
$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