brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: use s|old|new| in sed when your text is full of slashes

Sed
~/tips/tip-sed-custom-delimiter

sed 's/\/mnt\/user\/appdata\/old/\/mnt\/user\/appdata\/new/' app.conf

Swaps the slash in a sed replacement for another character, so paths stay readable.

Replacing a path with sed is where things get ugly. Every / in the path collides with the slashes of the s/old/new/ command, so you end up escaping them all and staring at something that looks like a fence.

The slash in an s command isn’t special. GNU sed lets you replace it with any other single character, as long as you use the same one all the way through. So this:

sed 's/\/mnt\/user\/appdata\/old/\/mnt\/user\/appdata\/new/' app.conf

becomes this:

sed 's|/mnt/user/appdata/old|/mnt/user/appdata/new|' app.conf

Same result, and you can read it. I like | for paths, # works too, and for URLs I’d pick whichever character doesn’t appear in the text. Flags like g still go at the end: s|old|new|g.

The same trick works in an address, with one difference: there you have to start it with a backslash. sed -n '\%^/home/%p' prints the lines that start with /home/, using % as the delimiter.

The caveat is that the character you pick is now the special one. If it shows up in your text, you have to escape it, so | is a bad choice when you’re editing a shell pipeline. And if the paths come from a variable, double check what’s in it before you run the command with -i.

Further reading: GNU sed manual

More Sed tips sed -n '$=' access.log echo 'hello world' | sed 's/.*/\U&/' printf 'key=1\nport=80\n' | sed '/^port=/a timeout=5' sed -n '210,218p' /etc/nginx/nginx.conf sed -i.bak 's/old-host/new-host/g' config.txt All Sed tips (6) All topics

Link