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: sed '0,/old/s//new/' changes only the first match in a whole file

Linux
~/tips/tip-linux-sed-first-match-only

sed '0,/^port=/s//port=8081 #/' app.conf

Replace the first occurrence in a file and leave every later one alone.

sed 's/old/new/' without g replaces the first match on every line, not the first match in the file. When a setting appears ten times and you only want to touch the first one, you need an address.

sed '0,/^port=/s//port=8081 #/' app.conf

Or in its simplest form:

sed '0,/foo/s//bar/' file.txt

The range 0,/foo/ runs from before the first line up to the first line that contains foo. The substitution only runs inside that range, and the empty pattern in s//bar/ reuses the last regular expression, here foo. So the first foo becomes bar, and every foo after it stays as it is.

Why 0 and not 1? With 1,/foo/ the end pattern is only checked from line two onward. If the very first line contains foo, the range would keep going until the next match, and you would replace two of them. Starting at 0 avoids that.

I’d check the output on screen first, and only then add -i to change the file itself. Address 0 is a GNU sed extension; BSD sed on macOS refuses it, so a script that uses it is not portable.

Further reading: GNU sed manual

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link