summaryrefslogtreecommitdiffstats
path: root/usr.sbin/bsdconfig/share
diff options
context:
space:
mode:
authordteske <dteske@FreeBSD.org>2013-05-16 16:46:02 +0000
committerdteske <dteske@FreeBSD.org>2013-05-16 16:46:02 +0000
commitced8469d7cf17e88de766790f154bc6ac69e262c (patch)
treef4143c09422a244f808f476048140ec64732c8ba /usr.sbin/bsdconfig/share
parent329247aec2da82ea7a5882d9c688a96b68113626 (diff)
downloadFreeBSD-src-ced8469d7cf17e88de766790f154bc6ac69e262c.zip
FreeBSD-src-ced8469d7cf17e88de766790f154bc6ac69e262c.tar.gz
Add a handy function for truncating variables to a specific byte-length. It
should be noted that newlines are both preserved and included in said byte- count. If you want to truncate single-line values without regard to line termination, there's always f_substr() which already exists herein.
Diffstat (limited to 'usr.sbin/bsdconfig/share')
-rw-r--r--usr.sbin/bsdconfig/share/strings.subr20
1 files changed, 20 insertions, 0 deletions
diff --git a/usr.sbin/bsdconfig/share/strings.subr b/usr.sbin/bsdconfig/share/strings.subr
index 73da04c..aec62ed 100644
--- a/usr.sbin/bsdconfig/share/strings.subr
+++ b/usr.sbin/bsdconfig/share/strings.subr
@@ -51,6 +51,26 @@ f_substr()
echo "$string" | awk "{ print substr(\$0, $start, $len) }"
}
+# f_snprintf $var_to_set $size $format ...
+#
+# Similar to snprintf(3), write at most $size number of bytes into $var_to_set
+# using printf(1) syntax (`$format ...'). The value of $var_to_set is NULL
+# unless at-least one byte is stored from the output.
+#
+f_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--
+ }'\' \)
+}
+
# f_longest_line_length
#
# Simple wrapper to an awk(1) script to print the length of the longest line of
OpenPOWER on IntegriCloud