Help getting a UNIX shell script to look at multiple files.

Hey everyone! I made a shell script that would go through a file and replace any phrase or letter with another phrase or letter. Helps update variable names or values. The following code is this:

#!/bin/sh

Word1="$1"
Replace1="$2"
File1="$3"

arg=$( echo "$Word1" | sed 's:[]\[\^\$\.\*\/]:\\&:g' )
sed -e "s/$arg/$Replace1/g" "$File1" > "$File1.updated"
mv "File1.updated" "$File1"

This works. Now I am trying to get it to do the same thing but for up to three files, and am running into problems.

I tried adding:

File2="$4"
File3="$5"

to cover the two additional files. However, how would I create a loop where it uses the above and then does it on the other two files?

The other thing I tried was adding the code after the first part:

while ["$File2" > 0];
do
sed -e "s/$arg/$Replace1/g" "$File2" > "$File2.updated"
mv "File2.updated" "$File2"
done

but that isn't working either. Any help?

Try using a while loop with shift to move the arguments down one:

#!/bin/bash

arg=$( echo "$1" | sed 's:[]\[\^\$\.\*\/]:\\&:g' )
Replace1="$2"

while [ $# -ge 3 ]
do
    File1="$3"
    sed -e "s/$arg/$Replace1/g" "$File1" > "$File1.updated"
    mv "$File1.updated" "$File1"
    shift
done

You could use a for loop, again using shift to bypass the first two values. Reasonably keeping to your original design:-

#!/bin/sh

Word1="$1"
Replace1="$2"
arg=$( echo "$Word1" | sed 's:[]\[\^\$\.\*\/]:\\&:g' )

shift 2             #  Drop first two arguments and move the others along

for File1 in $*     # Loop for all remaining arguments, i.e. the file names
do
   sed -e "s/$arg/$Replace1/g" "$File1" > "$File1.updated"
   mv "$File1.updated" "$File1"
done

This should run for however many files you list.

I hope that this helps,
Robin
Liverpool/Blackburn
UK

That should be "$@", or use for File1 do
Compare:

set -- 1 2 "3 4" 5 "6 7 8"
$ for i in $*; do
> echo "$i"
> done
1
2
3
4
5
6
7
8
$ for i in "$@"; do echo "$i"; done
1
2
3 4
5
6 7 8
$ for i ; do echo "$i"; done
1
2
3 4
5
6 7 8

# or one can even use:
$ for i do echo "$i"; done
1
2
3 4
5
6 7 8
1 Like