How to run VI in batch mode

Hi how do I use vi to do change some strings in a shell script loop

  1. Run ls first, for each file that contains the word salesreport*.txt, do the following
  2. use vi to run the following ex command : "1,$s/1975/1945/ig, wq"

Please tell me how to do this in vi, not sed. Thank you.

Hi.

The vi editor is another aspect of ex, so just use ex

You'll need to explicitly write the file, as well as exit, all with ex commands -- the wq should suffice for that.

When I use ed / ex, I usually use a here document for the commands:

ex file <<'EOF'
ex-command1
ex-command2
...
wq
EOF

... cheers, drl

Thanks,
may I ask what is the /bin/sh procedure for doing a loop on the output of ls:

imaginary code:
for filehandle in (ls salesreport*.txt):
do
ex filehandle <<'EOF'
1,$s/1975/1945/ig
wq
EOF
end

This is how you have to use the for loop..

for filehandle in `ls salesreport*.txt`
do
echo "->$filehandle<-"
done

Both of those for loops are broken. They will fail to properly handle filenames with IFS characters (by default a space, tab, or newline), and will fail if the result of the filename expansion exceeds the system's command line length limit (when attempting to execute the ls).

The simplest, most efficient, and safest way to iterate over the filenames matching that pattern is:

for filehandle in salesreport*.txt

Simple demonstration:

$ touch 'with space1' 'with space2'

$ # Broken code
$ for f in $(ls w*); do echo "$f"; done
with
space1
with
space2

$ # Correct code
$ for f in w*; do echo "$f"; done
with space1
with space2

Regards,
Alister

Hi, grossgermany.

You are welcome.

Meta-suggestions:

If someone is searching the forum for guidance on for loops, they might easily miss alister's excellent advice posted here because the title of the thread is How to run VI in batch mode, not about How to use loops. That's why it is best to start a new thread with an appropriate title for a new question. If necessary, you can include a reference to the old thread URL from the new thread.

Secondly, it is much easier to read code and data in threads when the text is surrounded by CODE tags. To do that almost effortlessly just select the text, and click the # symbol above the forum editing window. The result will be

like this

Best wishes ... cheers, drl