3

Suppose I have some statements in a shell (bash) script like

var=`cat file.txt`
echo "Date is: `date`"

I want to convert the backtick notation into $() notation like:

var=$(cat file.txt)
echo "Date is: $(date)"

How can I do this in Vim with search/replacement, for the entire file?

Motivation: https://github.com/koalaman/shellcheck/wiki/SC2006

1 Answer 1

5

You can try

:% s/`\([^`]*\)`/$(\1)/gc

g makes it global (for all entries in line), c makes vim to ask user about each replace.

But it won't work with nested backticks and multi-line code. Only for pairs backticks in line.

You can also quit from vim and use sed for this:

sed -n -i.backup 'N; ${s/`\([^`]*\)`/$(\1)/g; p; q}; b' filename

It will work with multi-line backtrics, but without nested.

3
  • Add a c after the g to manually confirm each substitution. I would also add double quotes around each $(...) but that might make things messy if you have backticks inside double quotes already. May be better to do that afterwards.
    – Kusalananda
    Jan 12, 2017 at 13:08
  • c modifier can be useful, yes. But i don't think it is really good idea to automatically wrap it into double quotes.
    – ValeriyKr
    Jan 12, 2017 at 13:12
  • Why would you wrap a statement like var=$(date) into doublequotes?
    – vatsug
    Jan 12, 2017 at 13:25

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.