severity 649147 wishlist
tags 649147 + fixed-upstream
quit

Hi Frank,

Frank Sell wrote:

> date +"%y-%m-%d %H:%M:%S" | mawk '{ printf ("%s %s\n", $2, substr($2, 0, 5)) 
> }'
> 08:57:41 08:5

POSIX sayeth:

        substr(s, m[, n ])

        Return the at most n-character substring of s that begins at
        position m, numbering from 1. If n is omitted, or if n
        specifies more characters than are left in the string, the
        length of the substring shall be limited by the length of the
        string s.

So "substr($2, 1, 5)" is the portable way to express what you meant.

That said, some nonportable scripts in the wild also use the semantics
implied by your example.  Therefore Thomas wrote the following patch.

-- >8 --
From: Thomas E. Dickey <dic...@invisible-island.net>
Date: Sun, 26 Jul 2009 12:39:02 +0000
Subject: tweak workaround for scripts that use substr(0, i)

makewhatis from man 1.6f uses (incorrectly...) substr(0,RSTART-1), and
that leaves mawk with a -1 initial index which it _adds_ to the length
rather than subtracting (probably not what anyone would expect).
Change the logic to subtract - and just for luck, account for the "1".
---
Hope that helps,
Jonathan

 CHANGES    |    9 +++++++--
 bi_funct.c |   11 ++++++++---
 2 files changed, 15 insertions(+), 5 deletions(-)

diff --git a/CHANGES b/CHANGES
index 97f514b2..812e0d92 100644
--- a/CHANGES
+++ b/CHANGES
@@ -1,8 +1,13 @@
 -- $MawkId$
 
 Changes by Thomas E Dickey <dic...@invisible-island.net>
 
-20090725
+20090726
+       modify workaround for (incorrect) scripts which use a zero-parameter
+       for substr to ensure the overall length of the result stays the same.
+       For example, from makewhatis:
+               filename_no_gz = substr(filename, 0, RSTART - 1);
+
        move regular-expression files into main directory to simplify building
        using configure --srcdir and VPATH.
 
diff --git a/bi_funct.c b/bi_funct.c
index 7da2fbc2..9435aaff 100644
--- a/bi_funct.c
+++ b/bi_funct.c
@@ -10,7 +10,7 @@ the GNU General Public License, version 2, 1991.
 ********************************************/
 
 /*
  * $MawkId$
  * @Log: bi_funct.c,v @
  * Revision 1.9  1996/01/14  17:16:11  mike
  * flush_all_output() before system()
@@ -258,12 +258,17 @@ bi_substr(CELL * sp)
     }
     i = d_to_i(sp[1].dval) - 1;        /* i now indexes into string */
 
+    /*
+     * Workaround in case someone's written a script that does substr(0,last-1)
+     * by transforming it into substr(1,last).
+     */
     if (i < 0) {
-       n += i;
+       n -= i + 1;
        i = 0;
     }
-    if (n > len - i)
+    if (n > len - i) {
        n = len - i;
+    }
 
     if (n <= 0)                        /* the null string */
     {
-- 
1.7.8.rc2




-- 
To UNSUBSCRIBE, email to debian-bugs-dist-requ...@lists.debian.org
with a subject of "unsubscribe". Trouble? Contact listmas...@lists.debian.org

Reply via email to