AIX

AIX

Connect with fellow AIX users and experts to gain knowledge, share insights, and solve problems.

 View Only
Expand all | Collapse all

Shell Script With Regular Exp in For Loop

  • 1.  Shell Script With Regular Exp in For Loop

    Posted Tue December 27, 2016 02:28 PM

    Originally posted by: JPJ2


    HI 

    I am new to Unix and Korn shell scripting.  I have a need to check to see if a file exists in a directory using a regular expression.  FYI, the script is running in the directory the file exists in.

    Example file to find = abc.txt_2017012212011111

    Regular Expression '^(abc\.txt_)[0-9]{16}$' works with grep from the command line.

    I would like to use this regex in a Korn shell script, but I am having trouble getting the above regex to work.

    This script worked with a wildcard:

    for f in abc*; do  
    
        [ -e "$f" ] && echo "files do exist" || echo "files do not exist"\
     break
    
    done
    

    But when I put the regex in insteady of the wildcard it doesn't work (shown below):

    for f in ^(abc\.txt_)[0-9]{16}$; do  
        [ -e "$f" ] && echo "files do exist" || echo "files do not exist"\
     break
    done
    

    I am not sure how to do this or why is doesn't work.  I have seen posts using grep to put it in a list then do a for loop off the list but I couldn't get this to work either.

    Any help is much appreciated.  Thanks!



  • 2.  Re: Shell Script With Regular Exp in For Loop

    Posted Wed December 28, 2016 02:08 PM

    Originally posted by: AncientAIXer


    I don't believe that the for command syntax accepts regex.  It will automatically expand the in expression as if it was done with the ls command.  When I do this I usually test my expression with the ls command and only be as specific as needed.  I would try something like: abc.txt_[0-9]*

    If you wish to use regex use something like:

    for f in $(ls | grep '^abc.txt_[0-9]')