💾 Archived View for jsreed5.org › log › 2021 › 202110 › 20211012-two-uses-for-grep.gmi captured on 2024-06-16 at 13:12:51. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2021-12-04)
-=-=-=-=-=-=-
---
While working on a bash script today, I ran into two tasks for which (GNU) grep provided an elegant solution.
The first task was to check if a nonempty string contained only digits, not all zero, with leading zeroes allowed. If the check passed, the string remained the same; otherwise the string was emptied. This check could be done in regex by using negative lookahead:
^(?!0+$)\d+$
However, I couldn't use this regex directly with bash builtins such as double brackets or the expr command. The shell treated the exclamation point in the lookahead as a history expansion before evaluating the regex, which of course threw an error. My solution involved echoing the string and piping it into grep:
string="$(echo "$string" | grep -P '^(?!0+$)\d+