Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate Regex from bash to zsh

I recently updated macOS to the new Catalina version and switched to zsh from bash as recommended. The problem is that in my workflow we do some file operations that need regular expressions and I can't figure out how to make it work with zsh.

Here's my two regexes:

ls | grep ^[0-9].*.chunk.js$
ls | grep ^main.*.chunk.js$

They should match the following files: main.d9a85e98.chunk.js and 2.c2cbac0f.chunk.js

Any ideas or resources?

Thank you!

like image 365
A Campos Avatar asked Sep 07 '25 05:09

A Campos


1 Answers

Quote the regular expression to prevent any attempts at shell expansion of the string before grep sees it.

# Ignoring the issue of parsing the output of ls
ls | grep '^[0-9].*.chunk.js$'
ls | grep '^main.*.chunk.js$'

A regular expression often can be interpreted as a shell pattern, which both bash and zsh will try to expand before running the command. Both shells have the option to treat a non-matching pattern as an error or as a literal string. By default, bash treats it as a literal string, while zsh treats it as an error. The "right" thing to do in either shell is to quote a string that you absolutely do not intend to be expanded as a pattern. bash just lets you get away with it more often.

In bash, this is controlled by the failglob option, which is off by default.

In zsh, it is controlled by the NOMATCH option, which is on by default.

zsh also has a much richer pattern language, so strings that may not have resulted in a pattern match in bash may do so in zsh. The result is the same: grep does not see the arguments you intended it to.

like image 199
chepner Avatar answered Sep 09 '25 01:09

chepner