I am trying to substitute words within multiple files...I posted the first script (http://www.unix.com/showthread.php?t=37505\) in tcsh and still for some reason getting nowhere so I tried it in ksh.
#!/bin/ksh
pattern1=$1
pattern2=$2
if [[ $# != 2 ]]
then
print "Usage: $0 $pattern1 $pattern2"
exit
fi
for file in $(ls)
do
sed "s/$pattern1/$pattern2/g" $file > $file
done
The problem is that when I run the script, it seems it gets to here
if [[ $# != 2 ]]
then
print "Usage: $0 $pattern1 $pattern2"
exit
fi
and never makes it to
for file in $(ls)
do
sed "s/$pattern1/$pattern2/g" $file > $file
done
because I don't see any changes made to the .txt files when I do
Alrighty...here's what I got (with your help...hopefully I did this right...just learning this stuff 2 weeks ago)
#!/bin/ksh
pattern1=$1
pattern2=$2
if [ $# -ne 2 ]
then
print "Usage: $0 $pattern1 $pattern2"
exit
fi
for file in *
do
cp $3 /tmp/$3
sed -e 's/$pattern1/$pattern2/g'/tmp/$3 > $3
done
Does that look about right?
BTW In case you wondering why I using $3. $3 is the name of the file in which to make the substitution.
I would also suggest that it is a bad way to write code for multiple commands, a proper if statement will be much more readable and easier to maintain.
i respectfully disagree. i have many scripts that use that type of logic and have never had a problem. i also have many scripts that use if/then with $?.
i typically use if/then on scripts that perform multiple or complex tasks, mostly (as you said) to make them easier to read.
You are of course entitled to do so, there is nothing syntactically or logically wrong with it, but I would suggest still that it is a bad way to code becasue you lose the structure and flow of the code.
My rationale:
Embedding programming logic in lines of code makes the program difficult to follow, the logic harder to find and debug. From experience this can cost money because it takes longer for someone else to learn/fix/extend the code which is always a probable situation in a professional setting.
If on the other hand it's for personal use, then anything goes.
each to his own i suppose - but as with any script small or large - it should be well commented. it is the documentation that makes it professional (given that it functions and is error correcting as well)