Read and edit multiple files using a while loop

Hi all,
I would like to simply read a file which lists a number of pathnames and files, then search and replace key strings using a few vi commands:

:1,$s/search_str/replace_str/g<return>

but I am not sure how to automate the <return> of these vis commands when I am putting this in a while loop.

i.e. if a loop the first time I cannot actually initiate the above command without pressing the return button, is there a special command for this?

Thanks

The syntax you use can be also used in sed. If your sed has the -i option (perl has an option like this too), you can just edit the files directly. Else you might want to write the output of sed to a tmp file and mv it back to the original file.
If you can print the files with a find and hand them over to sed -i with -exec or xargs for example.
If you feed the filenames from a file, then a while loop may be a good idea.

Sorry not too familiar with SED commands so breaking this down so I have tried this comamnd:

sed -e '1,$s/old string/new string/g' myfirstfileinloop.txt

now when I execute this it prints to the terminal including the new strings that were replaced yet when I open the actual file it still remains the old same and nothing has changed?

Ok!

We have two options:

  1. As zaxxon commented, if your sed supports the "-i" option, in place change, use it.
sed -i -e '1,$s/old string/new string/g' myfirstfileinloop.txt
  1. If it does not, you must redirect the output, like the following:
ls -1 | while read fname
do
      myFileTmp=${fname}.tmp
      sed -e '1,$s/old string/new string/g' "${fname}" > "${myFileTmp}"
      # If you want to remove the original file uncomment the line below
      [ $? -eq 0 ] && rm -f "${fname}"
done

The second option will change all files in a directory, you want one file, just:

sed -e '1,$s/old string/new string/g' myfirstfileinloop.txt > myfirstfileinloop.txt.new

Also, in the second option you can rename the tmp file to the original one:

ls -1 | while read fname
do
      myFileTmp=${fname}.tmp
      sed -e '1,$s/old string/new string/g' "${fname}" > "${myFileTmp}"
      # If you want to change back to the original file uncomment the line below
      # [ $? -eq 0 ] && mv "${myFileTmp}" "${fname}"
done

It supports sed but it seems to throw this illegal message:

sed: illegal option -- i
Usage: sed [-n] [-e script] [-f source_file] [file...]

It is because sed does not support the: "-i" option. Try the second option.

Also, in what platform are you executing it?

Regards.

will try, the platform is HP-UX

---------- Post updated at 03:04 AM ---------- Previous update was at 02:36 AM ----------

Its the HP Unix platform

Regards

Were you able to test it?