Find the answer to your Linux question:
Results 1 to 3 of 3
Hi All, how do I get this regular expression to work in an if/else statement? This is just a little script for learning BASH. Please don't be too harsh. Thanks. ...
  1. #1
    Just Joined!
    Join Date
    Dec 2005
    Posts
    10

    Regular Expression in String Comparison

    Hi All,

    how do I get this regular expression to work in an if/else statement? This is just a little script for learning BASH. Please don't be too harsh. Thanks.

    Code:
    #!/bin/sh
    #
    #
    #This script will test if a certain number of files with 1-4 in their filename exist and print their filename. An error message will be printed if not.
    #
    for i in `ls file[1-9]`
    do
    if [[ "$i" == *1-4 ]] ; then
            echo "This file, $i, ends in a number between 1-4"
    else
            echo "Error, this file, $i, does not end with a number between 1-4"
    fi
    done
    I get this error.

    ./file_test.sh: 13: [[: not found

  2. #2
    Linux Enthusiast Kloschüssel's Avatar
    Join Date
    Oct 2005
    Location
    Italy
    Posts
    717
    Code:
    #!/bin.bash
    FILES="$@"
    regex="[1-4]+"
    for f in $FILES
    do
    if [[ $f =~ $regex ]]; then
     echo "$f : yes";
    else
     echo "$f : no";
    fi
    done
    and use it like this:

    Code:
    has_1_to_4_in_name mydir/*
    Mostly got all information from google, which lead me here.

    EDIT: I like the signature of the above post; well .. learn to use google. some may offer a workshop?

  3. #3
    drl
    drl is offline
    Linux Engineer drl's Avatar
    Join Date
    Apr 2006
    Location
    Saint Paul, MN, USA / CentOS, Debian, Solaris, SuSE
    Posts
    1,117
    Hi.

    I would use bash, ksh, or zsh in place of sh ... cheers, drl
    Welcome - get the most out of the forum by reading forum basics and guidelines: click here.
    90% of questions can be answered by using man pages, Quick Search, Advanced Search, Google search, Wikipedia.
    We look forward to helping you with the challenge of the other 10%.
    ( Mn, 2.6.n, AMD-64 3000+, ASUS A8V Deluxe, 1 GB, SATA + IDE, Matrox G400 AGP )

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...