3

What I usually do from bash/vim ... is

  • open file with vim
  • go to line to comment
  • comment a line
  • save and quit

My file is /usr/local/etc/php/7.0/conf.d/ext-xdebug.ini and the initial content is

[xdebug]
zend_extension="/usr/local/opt/php70-xdebug/xdebug.so"

I want to run a command that in one statement adds ; at the beginning of the second line.

[xdebug]
zend_extension="/usr/local/opt/php70-xdebug/xdebug.so"

Is it possible to do this directly from bash?

  • this is trivial to do with command line text processing tools like sed.. for ex: sed -i '2 s/^/;/' file to add ; at beginning of 2nd line and sed -i '2 s/.//' file to delete first character from 2nd line... see this for more such examples and this for use of -i flag for different sed versions – Sundeep Oct 28 '16 at 13:57
  • 1
    also, I think you missed out adding ; in question to show before and after example – Sundeep Oct 28 '16 at 13:58
5

You can use:

vim +'normal! 2GI;' +'x' path/to/your/file

The + parameter allows to execute a command after opening the buffer.

The first command normal! 2GI; goes to line 2 and add a ; at the beginning of the line

The second command saves and exit.


Bonus point: To uncomment the same line:

vim +'normal! 2G^x' +'x' path/to/your/file
  • What exactly second param "+'x'" means? – sensorario Oct 28 '16 at 9:14
  • 1
    @sensorario See :h :x. The command :x is the equivalent of the command :wq i.e. save and exit. – statox Oct 28 '16 at 9:16
  • :x is not fully equivalent to :wq as it does not write when there are no changes (timestamp is preserved) – Andrey R Oct 28 '16 at 13:55

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.