简体   繁体   English

如何比较bash中的两个字符串?

[英]How can I compare two strings in bash?

I am trying to remove all ".s" files in a folder that can be derived by ".c" source files. 我正在尝试删除可以由“ .c”源文件派生的文件夹中的所有“ .s”文件。 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. 但是此代码将删除所有“ .s”文件。 I think it's not comparing the filenames properly. 我认为它没有正确比较文件名。 Can someone please help. 有人可以帮忙吗?

The canonical way to compare strings in bash is: 比较bash中字符串的规范方法是:

if [ "$string1" == "$string2" ]; then

this way if one of the strings is empty it'll still run. 这样,如果其中一个字符串为空,它将仍然运行。

You can use it like this: 您可以像这样使用它:

[[ "$cfile" = "$sfile" ]] && rm "$sfile"

OR 要么

[[ "$cfile" == "$sfile" ]] && rm "$sfile"

OR by using old /bin/[ (test) program 或通过使用旧的/bin/[ (测试)程序

[ "$cfile" = "$sfile" ] && rm "$sfile"

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. 只需保留比较代码即可。

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). 它仅列出所有.c文件并尝试删除相应的.s文件(如果有)。

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 : 您也可以蛮力删除所有内容,然后将错误消息重定向到/dev/null

for cFile in *.c; do
    sFile="${cFile%c}s"
    rm "$sFile" &> /dev/null
done

but this will be slower of course. 但这当然会慢一些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM