简体   繁体   中英

How can I give special command (insert) to vi?

I remember doing magic with vi by "programming" it with input commands but I don't remember exactly how.

My sepcial request are:

  • launch vi in a script with command to be executed.
  • do an insert in one file.
  • search for a string in the file.
  • use $VARIABLE in the vi command line to replace something in the command.
  • finish with :wq .

I my memory, I sent the command exactly like in vi and the ESC key was emulate by '[' or something near.

I used this command into script to edit and change files.

I'm going to see the -c option but for now I cannot use $VARIABLE and insert was impossible (with 'i' or 'o').

#!/bin/sh
#

cp ../data/* .

# Retrieve filename.
MODNAME=$(pwd | awk -F'-' '{ print $2 }')

mv minimod.c $MODNAME.c

# Edit and change filename into the file (from mimimod to the content of $VARIABLE).
vi $MODENAME.c -c ":1,$s/minimod/$MODNAME/" -c ':wq!'

This example is not functionning (it seems the $VARIABLE is not good in -c command).

Could you help me remember memory ;) ?

Thanks a lot. Joe.

You should not use vi for non-interactive editing. There's already another tool for that, it's called sed or stream editor .

What you want to do is

sed -i 's/minimod/'$MODNAME'/g' $MODNAME.c

to replace your vi command.

Maybe you are looking for the ex command, that can be run non-interatively:

ex $MODENAME.c <<< "1,\$s/minimod/$MODNAME/
wq!
"

Or if you use an old shell that does not implement here strings :

ex $MODENAME.c << EOF
1,\$s/minimod/$MODNAME/
wq!
EOF

Or if you do not want to use here documents either:

echo "1,\$s/minimod/$MODNAME/" > cmds.txt
echo "wq!" >> cmds.txt
ex $MODENAME.c < cmds.txt
rm cmds.txt

One command per line in the standard input. Just remember not to write the leading : . Take a look at this page for a quick review of ex commands.

Granted, it would be better to use the proper tool for the job, that would be sed , as @IsaA answer suggests, or awk for more complex commands.

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