简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM