Skip to content

Comment on A digital circuit simulator written in sed

Comments

I just recently decided to skim the GNU Sed manual and it honestly doesn't surprise me one bit that this is possible. Sed is basically a bytecode VM that only does string manipulation.

Did you acquire any useful new tricks from this experience?

Yeah, it was interesting to learn how sed addresses[0] work, particular regex and range addresses in combination.

Basically, you can select a range of lines using regexes. For example, if I wanted to get the text under one header in a Markdown document, I could write something like this:

  sed -n '/^## Overview/,/^#/ { /^#/b; p }' README.md

  - The '-n' flag tells sed not to print all matched lines by default.
  - '/^## Overview/,/^#/' is a range address that matches all lines from
    one starting with "## Overview" to another line starting with "#", inclusive.
  - '{ /^#/b; p }' is a command group that's executed for each matched line.
  - '/^#/b' uses the 'b' (branch) command to skip lines starting with "#" to
    avoid printing the header lines, which are included in the range.
  - Finally, 'p' is the print command, which tells sed to print all the other
    lines.
That said, I mainly read it because I've always used things like Bash's built-in parameter expansion[1] and regex capability[2] instead of sed, and I mostly think I confirmed that bias. I'll probably turn to sed for certain string manipulations from now on, but I'm not sure I'll be using it a whole lot more often.

[0] https://www.gnu.org/software/sed/manual/sed.html#sed-address... [1] https://wiki.bash-hackers.org/syntax/pe [2] https://www.linuxjournal.com/content/bash-regular-expression...

I didn’t know sed could do that. It seems that vim’s s(ubstitute) utility also has the same features with a near-identical syntax.

https://vim.fandom.com/wiki/Search_and_replace

Thanks for sharing!

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.