A Tutorial for the Sam Command Language

1 month ago 2

The x command is, in my opinion, the key to what makes the sam command language so brilliant. It’s short for "extract", but I came to think of it as a "for each" loop.

This example will replace every "hello" with "bye":

The , address is short for 0,$, which initially selects the entire document (another sam idiom!). x/hello/ is, "for each selected match of 'hello'…​" And c/bye/ means, "replace the selection with 'bye'."

Of course, that’s just a find-and-replace. Here’s an equivalent substitute command in Vim:

But whereas ex/vi/Vim’s s is specialized and only does substitution. x can run any command, such as d (delete).

This deletes all shell-style comments:

To do something for every line in a file in sam:

Ah, you say, but this is just like ex/vi/Vim’s g ("global") command, which can also run arbitrary commands for every pattern match…​

You are correct. But we’re only scratching the surface. How about conditionals?

Here’s conditionals with sam’s g for "guard":

(Sorry, I know it’s confusing to mention ex/vi/Vim’s g and then show sam’s g. They’re not the same.)

I think of sam’s g as an "if" statement.

So the above reads to me as "for each line, if it contains the string 'foo', delete that line."

Note that the d for delete still applies to the entire line. That’s because g/foo/ means "…​if it contains 'foo'". Like an "if" statement, g doesn’t select a match, it just determines if we should continue.

Read Entire Article