Reputation: 423
I am trying to remove all ".s" files in a folder that can be derived by ".c" source files. This is my code
for cfile in *.c; do
#replace the last letter with s
cfile=${cfile/%c/s}
for sfile in *.s; do
#compare cfile with sfile; if exists delete sfile
if [ $cfile==$sfile ]; then
rm $sfile;
fi
done
done
But this code deletes all the ".s" files. I think it's not comparing the filenames properly. Can someone please help.
Upvotes: 0
Views: 90
Reputation: 7332
I think the most simpliest solution would be:
for cfile in *.c ; do rm -f "${cfile%.c}.s" ; done
It just lists all the .c
files and try to delete the corresponding .s
file (if any).
Upvotes: 1
Reputation: 15320
for cFile in *.c; do
sFile="${cFile%c}s"
if [[ -f "$sFile" ]]; then
echo "delete $sFile"
fi
done
The actual deletion of the files I leave as an exercise. :-)
You can also just brute force and delete everything and redirecting the error messages to /dev/null
:
for cFile in *.c; do
sFile="${cFile%c}s"
rm "$sFile" &> /dev/null
done
but this will be slower of course.
Upvotes: 0
Reputation: 123528
Saying
if [ $chile==$sfile ]; then
would always be true since it amounts to saying
if [ something ]; then
Always ensure spaces around the operators.
The other problem is that you're saying:
cfile=${cfile/%c/s}
You probably wanted to say:
sfile=${cfile/%c/s}
And you need to get rid of the inner loop:
for sfile in *.s; do
done
Just keep the comparison code.
Upvotes: 1
Reputation: 785266
You can use it like this:
[[ "$cfile" = "$sfile" ]] && rm "$sfile"
OR
[[ "$cfile" == "$sfile" ]] && rm "$sfile"
OR by using old /bin/[
(test) program
[ "$cfile" = "$sfile" ] && rm "$sfile"
Upvotes: 1
Reputation: 27577
The canonical way to compare strings in bash is:
if [ "$string1" == "$string2" ]; then
this way if one of the strings is empty it'll still run.
Upvotes: 2