I have to delete every word containing at least one number from each file given through the command line as parameter. This is my code:
while [ "$*" != "" ]; do
if [ ! -f $1 ]
then echo "$1 not file"
else
sed -ie "s/[^ ]*[0-9][^ ]*//g" $1
fi
shift
done
It works perfectly if I have only one file, but if I have more it gives the same result for each. After I run the script in each file there will be the result of the first one.
Can someone tell me what I’m missing?
EDIT2:
This is what I’m running now:
while [ "$#" -ne 0 ]; do
for file in "$@"; do
if [ ! -e "$file" ]; then
printf "file doesn't exist: %s\n" "$file"
continue;
fi
if [ ! -f "$file" ]; then
printf "not a file: %s\n" "$file"
continue;
fi
done
sed -i "s/[^ ]*[0-9][^ ]*//g" "$file"
done
I was talking about the done for the while loop and the done for the for loop; but even without that my script keeps running.
EDIT:
Basically the same thing just a bit different. I have to delete the second and fourth word from each line from each file (word only contain alphanumeric characters). Its’ not working properly and I cant find the error. This is my code:
while [ "$*" != "" ]; do
if [ ! -f $1 ]
then echo "$1 not file"
else
sed -ie 's/^\( *[^ ]+\) +[^ ]+\(.*\)/\1\2/
s/^\( *[^ ]+\)\( +[^ ]+\) +[^ ]+\(.*\)/\1\2\3/g' $1
fi
shift
done
the while loop condition should check if there are no arguments, and if there are it should continue. So the right form would be
Now, what you really want is to get each argument and do something with it. That automatically implies a for loop. So what you really should be doing is
Now, a file can have spaces in it, so getting that filename and checking if it is really a file should be quoted, and you should also check for existance first
I could expand more on
sedwhere the-iswitch is restricted only to GNU sed. Apart from that you may also want to keep a backup of that file in case something goes wrong.But this is another topic I guess.