2

I often use ex in scripted edits. I can run several editing commands, and then save the changed file, with no danger of hanging if an ex command encounters an error, by running commands like so:

printf '%s\n' '%s/someregex/somereplacementtext/g' x | ex file.txt

To test commands before overwriting the file, I use:

printf '%s\n' '%s/someregex/somereplacementtext/g' %p 'q!' | ex file.txt

However, I've just encountered a need to simply print a certain line number and then exit.

I know the ex command ".=" will print the current line number when editing interactively. Unfortunately, I've found that this doesn't print to stdout the way that p does. You can see this for yourself:

printf '%s\n' '8p' '8=' 'q!' | ex somefile.txt

How can I make the .= command print to stdout from a scripted ex instance?

1
  • Do you need the line number on its own? .# will print the current line prefixed with the line number.
    – Antony
    Nov 4 '16 at 0:18
1

You need to enable line numbering by calling :set nu

$ printf '%s\n' 'set nu' '%s/Quux/Foo/g' %p 'q!' | ex file.txt
     1  Foo Bar
     2  Foo Foo Bar Bar
     4  Bar Bar Bar
     5  Foo Foo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.