0

I am trying to replace positional arguments with variables in my bash script using Vim's substitute :scommand.

Example: I would like to replace the following text in a bash script:

python3 mymodule.py --dataversion $1

with:

python3 mymodule.py --dataversion "${DATAVERSION}"

I have tried :s/\$1/"${DATAVERSION}" resulting in E486: Pattern not found: $1.

When I search the pattern instead of substituting, /\$1, the instances are detected. Why is this pattern different in Vim's search and susbstitute commands?

  • 3
    your vim command will only do the replacement on the current line -- prepend it a % if you want to do the search and replace in the whole file. – mosvy Dec 30 '19 at 17:33
  • 2
    What mosvy said, also, you don't have to escape the $ as it is not the last character in the pattern. – Kusalananda Dec 30 '19 at 19:10
0

When you search, Vim will automatically consider the entire buffer (provided you haven't disabled the 'wrapscan' option - then it would only search until the end). Your :substitute command only considers the current line, as you've left out the :help :range, and this command (like most others) defaults to the current line only. To cover the entire buffer for your substitution, just prepend %, which is an abbreviation for 1,$:

:%s/\$1/"${DATAVERSION}"

Also, if there were multiple occurrences of $1 in a line, only the first one would be replaced. Append /g for a global substitution.

As mentioned in the comments, the $ does not need to be escaped (it only has special meaning at the end of the pattern), but it's fine to escape it, too (and avoids some thinking).

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.