]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
lib/strutils: add ul_strchr_escaped()
authorKarel Zak <kzak@redhat.com>
Mon, 2 May 2022 13:07:42 +0000 (15:07 +0200)
committerKarel Zak <kzak@redhat.com>
Wed, 20 Jul 2022 15:35:52 +0000 (17:35 +0200)
Like strchr(), but ignores escaped chars.

Signed-off-by: Karel Zak <kzak@redhat.com>
include/strutils.h
lib/strutils.c

index ae689a30ad22939456dad9af3c86836adf8e09a5..ea102723d8ab38ae5dec73749775101d76812449 100644 (file)
@@ -389,6 +389,8 @@ extern int strappend(char **a, const char *b);
 
 extern const char *split(const char **state, size_t *l, const char *separator, int quoted);
 
+extern char *ul_strchr_escaped(const char *s, int c);
+
 extern int skip_fline(FILE *fp);
 extern int ul_stralnumcmp(const char *p1, const char *p2);
 
index e85d265d2d273c6141e721653b3329523be4ba8b..104eb3887dad61e0bdfa9bd84837c3f398523a0f 100644 (file)
@@ -1035,6 +1035,37 @@ static size_t strcspn_escaped(const char *s, const char *reject)
         return n - escaped;
 }
 
+/*
+ * Like strchr() but ignores @c if escaped by '\', '\\' is interpreted like '\'.
+ *
+ * For example for @c='X':
+ *
+ *      "abcdXefgXh"    --> "XefgXh"
+ *     "abcd\XefgXh"   --> "Xh"
+ *     "abcd\\XefgXh"  --> "XefgXh"
+ *     "abcd\\\XefgXh" --> "Xh"
+ *     "abcd\Xefg\Xh"  --> (null)
+ *
+ *     "abcd\\XefgXh"  --> "\XefgXh"   for @c='\\'
+ */
+char *ul_strchr_escaped(const char *s, int c)
+{
+       char *p;
+       int esc = 0;
+
+       for (p = (char *) s; p && *p; p++) {
+               if (!esc && *p == '\\') {
+                       esc = 1;
+                       continue;
+               }
+               if (*p == c && (!esc || c == '\\'))
+                       return p;
+               esc = 0;
+       }
+
+       return NULL;
+}
+
 /* Split a string into words. */
 const char *split(const char **state, size_t *l, const char *separator, int quoted)
 {
@@ -1262,6 +1293,10 @@ int main(int argc, char *argv[])
                printf("'%s'-->%hu\n", argv[2], strtou16_or_err(argv[2], "strtou16 failed"));
                return EXIT_SUCCESS;
 
+       } else if (argc == 4 && strcmp(argv[1], "--strchr-escaped") == 0) {
+               printf("\"%s\" --> \"%s\"\n", argv[2], ul_strchr_escaped(argv[2], *argv[3]));
+               return EXIT_SUCCESS;
+
        } else {
                fprintf(stderr, "usage: %1$s --size <number>[suffix]\n"
                                "       %1$s --cmp-paths <path> <path>\n"