Today I’m going to share a Linux tip that has changed lives.
OK, maybe that’s an overstatement, but every time I’ve shown it to someone, they say “Really!?!? OMG that’s so much easier.” Technically, anyone reading docs could find it, because it’s not secret or undocumented. However, there’s such powerful tradition in Unix/Linux circles that people grow up learning painful ways of doing things. Even this week, I talked with a guy who’s been a Unix/Linux sysadmin since before Linux existed and he didn’t know this trick.
This is applicable to Linux, BSD, and older proprietary Unices. I was shown this on SunOS decades ago, so it goes back to the origins of Unix. It also applies to working in vi/vim, perl, and nearly anywhere regular expressions are used.
The Problem: Backslashitis
I’ll give you an example involving file names, but again, this trick is universal for regular expressions.
Let’s imagine you have a path like this in a shell script:
/some/path/that/is/long
You want to change it to:
/some/path/new/path
How would you do it? A regular expression of course. Let’s use sed. I’m sure you’ve seen things like this:
sed 's/\/that\/is\/long/\/new\/path/'
That works, but it’s confusing to read, isn’t it? Let’s put the actual delimiters in red:
sed 's/\/that\/is\/long/\/new\/path/'
Unfortunately, because you’re using / as your delimiter, you have to escape it wherever you use it otherwise with backslashes, which leads to backslashitis.
The Cure
Did you know you use any character as a delimiter in a regular expression? Try this:
sed 's#/that/is/long#/new/path#'
Whoa! That’s sure a lot easier to read, isn’t it? By replacing the red slashes above with octothorps, I no longer need to escape slashes.
Of course, if your string is full of octothorps, use something else. You can even use spaces:
sed 's /that/is/long /new/path '
As long as the delimiter is the same in all three places, any symbol will work.
You can do this with any regular expression. I’ve seen people (and have myself) struggle with getting the right backslashes in the right place, count them, and agonize over complex regular expressions because visually they’re hard to parse. With this trick, everything becomes so much simpler.
Enjoy!
Related Posts:
- “OMG! I Never Knew That!”: The Simply Linux Tip That Has Got Me More Thanks Than Anything I’ve Ever Shared in 30+ Years - January 19, 2025
- Bluesky has Flopped: How Mashable is Lying To You - January 18, 2025
- Bonus Code Friday!Vote For Your Favorite Video Game to Play on the Arcade You Could Win from RackNerd! - January 17, 2025
Leave a Reply