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.

Inian
  • 12,472
  • 1
  • 35
  • 52

1 Answers1

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

JdeBP
  • 66,967
  • 12
  • 159
  • 343
  • Worked just like charm! It's great that even after 30 years, the old tools just work awesome. – Inian Feb 08 '18 at 17:38