0

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.

1
  • You don't need a nested loop here. Commented Oct 4, 2013 at 12:07

5 Answers 5

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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"

Comments

1

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.

Comments

1

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).

Comments

0
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.

1 Comment

Consider upvoting and accepting a reply if it answered your question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.