How do you check if a file ends in a certain file extension in bash? - eviltoast

Seriously. There doesn’t seem to be a way to do this. Every thing I ever try I just get bad substitution errors. The internet is full of people posting code that’s supposed to compare file extensions but none of it works. I’ve spent all morning trying everything I could find. I already gave up and I’m making this progeam in python instead but now I’m curious. How tf do you actually compare file extensions? If I have a folder fill of files and I want to run a command only on the png files, there seems to be no way to actually do this.

If someone posts “[[ $file == *.txt ]]” I’m going to fucking scream because THAT DOES NOT WORK. IT’S NOT VAILD BASH CODE.

      • manicdave@feddit.uk
        link
        fedilink
        English
        arrow-up
        3
        arrow-down
        1
        ·
        5 months ago

        ls returns a list of files, the pipe passes that list to grep. The grep only returns results that match the string txt$. The $ symbol represents an end of line.

        • Korthrun@lemmy.sdf.org
          link
          fedilink
          English
          arrow-up
          5
          ·
          edit-2
          5 months ago

          That’s my bad, I asked an incomplete question.

          What does the approach of spawning a grep process and having ls send ALL of it’s output to grep have over just passing a glob to ls?

          Like:

          $ ls /usr/share/*.lm
          
          /usr/share/out-go.lm  /usr/share/ril.lm     /usr/share/rlhc-crack.lm   /usr/share/rlhc-d.lm   /usr/share/rlhc-java.lm  /usr/share/rlhc-julia.lm  /usr/share/rlhc-ocaml.lm  /usr/share/rlhc-rust.lm
          /usr/share/ragel.lm   /usr/share/rlhc-c.lm  /usr/share/rlhc-csharp.lm  /usr/share/rlhc-go.lm  /usr/share/rlhc-js.lm    /usr/share/rlhc-main.lm   /usr/share/rlhc-ruby.lm
          
          • manicdave@feddit.uk
            link
            fedilink
            English
            arrow-up
            2
            ·
            edit-2
            5 months ago

            Tbh, I didn’t even realise you could do that. I’m just used to using grep and worked backwards. Thanks for pointing it out.