Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we match a suffix in a string in bash?

I want to check if an input parameter ends with ".c"? How do I check that? Here is what I got so far (Thanks for your help):

#!/bin/bash

for i in $@
do
    if [$i ends with ".c"]
    then
            echo "YES"
        fi
done
like image 603
Dave Avatar asked Oct 18 '11 05:10

Dave


People also ask

What does %% mean in bash?

So as far as I can tell, %% doesn't have any special meaning in a bash function name. It would be just like using XX instead. This is despite the definition of a name in the manpage: name A word consisting only of alphanumeric characters and under- scores, and beginning with an alphabetic character or an under- score.

How do you equal a string in bash?

When comparing strings in Bash you can use the following operators: string1 = string2 and string1 == string2 - The equality operator returns true if the operands are equal. Use the = operator with the test [ command. Use the == operator with the [[ command for pattern matching.

How do I find a character in a string in bash?

Another option to determine whether a specified substring occurs within a string is to use the regex operator =~ . When this operator is used, the right string is considered as a regular expression. The period followed by an asterisk . * matches zero or more occurrences any character except a newline character.

How do I select a substring in bash?

Using the cut Command Specifying the character index isn't the only way to extract a substring. You can also use the -d and -f flags to extract a string by specifying characters to split on. The -d flag lets you specify the delimiter to split on while -f lets you choose which substring of the split to choose.


2 Answers

A classical case for case!

case $i in *.c) echo Yes;; esac

Yes, the syntax is arcane, but you get used to it quickly. Unlike various Bash and POSIX extensions, this is portable all the way back to the original Bourne shell.

like image 171
tripleee Avatar answered Oct 29 '22 23:10

tripleee


$ [[ foo.c = *.c ]] ; echo $?
0
$ [[ foo.h = *.c ]] ; echo $?
1
like image 40
Ignacio Vazquez-Abrams Avatar answered Oct 29 '22 21:10

Ignacio Vazquez-Abrams