0

I like using the traditional ex editor for simple command line operations, to re-arrange text within files. For example for a simple moving lines across in a file I would use something like

foo
bar
zoo
dude

to move the text dude after foo I would just do

printf '%s\n' '/dude' 'd' '/foo' '-' 'put' 'wq' | ex file

which means move to pattern dude, put the line in buffer and paste it after foo and wq to close the file.

This works fine so far, but I want to insert my custom text to the file, given for example

 example
//commented
 abc
 def

I need to add another text above //commented if pattern abc matches i.e. in a file if abc is present and above it if a line starting with // exists add another line //new text, so it should look like

 example
//new text
//commented
 abc
 def

I tried to do below, using itextESC to insert text, but it is not working.

printf '%s\n' '/abc' '-' '/\/\/' 'itextESC' 'wq' | ex file

I would like to make this work in ed or ex to explore more about this tool. Would appreciate insights if ed/ex can be used for such trivial tasks like this.

2

Don't expect visual commands to work in ex mode. Do use the actual ex commands for inserting text, a[ppend] and i[nsert].

printf '%s\n' '/abc' '-' '/\/\/' 'i' 'text' '.' 'wq' | ex file

Further reading

  • Worked just like charm! It's great that even after 30 years, the old tools just work awesome. – Inian Feb 8 '18 at 17:38

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.