QuantumLicht
QuantumLicht

Reputation: 2183

Use vim in bash script to replace characters

I want to build a small util script that will replace characters in a given file. Here's what I have so far. When I run this, I see my echo messages, but the program never returns. If I manually exit the program, there is no effect. So it seems it is hanging somewhere, but I can't be sure why.

sEnv=$1
eEnv=$2
reverseArgs=$3
echo ${reverseArgs}
if [ "$3" == "-r" ]; then
   echo "changing from ${eEnv} to ${sEnv}"
   cmd="vim -E -s /Users/X/nginx.conf << EOF\
   :%s/${eEnv}/${sEnv}/g\
   :wq\
   EOF"
   `${cmd}`
else
   echo "changing from ${sEnv} to ${eEnv}"
   cmd="vim -E -s /Users/X/nginx.conf << EOF\
   :%s/${sEnv}/${eEnv}/g\
   :wq\
   EOF"
   `${cmd}`
fi
EOF

I know it is supposed to work, because if I just put this in my script it works:

vim -E -s /Users/X/nginx.conf << EOF
   :%s/${eEnv}/${sEnv}/g
   :wq
   EOF

Upvotes: 1

Views: 450

Answers (2)

John Bollinger
John Bollinger

Reputation: 180113

As @trojanfoe first suggested, you should use sed for a job like this. It's better suited:

sed -i "s/${eEnv}/${sEnv}/g" ${file}

It would be possible to do it with vim, though. The reason your attempt does not work is that you are building the command to execute as a string, and in doing so, crushing your heredoc into an ordinary string. I don't see why that's useful, when you could just execute the command directly:

vim -E -s /Users/philippeguay/nginx.conf << EOF
:%s/${sEnv}/${eEnv}/g
:wq
EOF

Upvotes: 3

meuh
meuh

Reputation: 12255

not sure why you go via variable cmd. Try:

sEnv=$1
eEnv=$2
reverseArgs=$3
echo ${reverseArgs}
if [ "$3" == "-r" ]; then
   echo "changing from ${eEnv} to ${sEnv}"
   vim -E -s - /Users/X/nginx.conf <<EOF
   :%s/${eEnv}/${sEnv}/g
   :wq
EOF
else
   echo "changing from ${sEnv} to ${eEnv}"
   vim -E -s - /Users/philippeguay/nginx.conf <<EOF
   :%s/${sEnv}/${eEnv}/g
   :wq
EOF
fi

I added -s - for my vim else it takes the filename as a script, I think. Note the EOF must not be indented.

Upvotes: 2

Related Questions