How should I handle errors in ex scripts without waiting for user input?

StackOverflow https://stackoverflow.com/questions/16526147

  •  29-05-2022
  •  | 
  •  

سؤال

I'm trying to perform a search/replace with an ex script (targeting vim's ex implementation), as so:

ex -qc 'g/^[#][[:space:]]*$/d|x' file.txt

However, when file.txt already contains no matching content, the script hangs; when run without -q, it additionally displays the error below:

E486: Pattern not found: ^[#][[:space:]]*$

How can I build this script to continue (or, better, abort and immediately exit) on failure, rather than awaiting user input?

I'm using ex in favor of sed -i due to portability constraints (in-place edit support being a GNU extension to sed, and not available on all platforms).

هل كانت مفيدة؟

المحلول

Send vim a separate quit command with -c 'q', which it will execute after the search/replace (works on my vim version 7.3.315):

ex -c 'g/^[#][[:space:]]*$/d|x' -c 'q' file.txt

Also note ex appears to execute the commands in the order which they appear in ARGV, so:

ex -c 'q' -c 'g/^[#][[:space:]]*$/d|x' file.txt

Quits before doing the search/replace.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top