1

Using the following example, I am trying to figure it out the regex which cover the following pattern in my awk program.

  • The output could be only numbers no more than 5 length : i.g. 15251
  • The output could have two letters only "H" & "O" and any numbers before =< 3 and after =< 5 and "O" could be optional: i.g HO722 or 799H89090
  • The output could NOT include anything that has space or any words except digits :i.g hkks kjsla aaa --> not acceptable

    cat filename

    00ISM00123
    189902
    078HP890201
    HO90902
    123H7292
    234HO7027
    12345556
    GV18029039
    kslal HOsjlk jj 123
    687iOu7900
    

I tried the following script

 awk  '$1~/^[0-9]{,3}([hH][oO]?)[^a-zA-Z]/' filename`

but dose not cover the digits in filename i.e.

>     189902 
>     12345556

when I tried the following script still the output is not correct as expected!

awk  '$1~/^([0-9]{,3}([hH][oO]?)?)[^a-zA-Z]/' filename

any help with explanation is highly appreciate it!

1

I split this up into two regexes, this looks like it is working :

cat filename | grep -E '^[0-9]{5}$|^[0-9]{0,3}[hH]{1}[oO]{0,1}[0-9]{0,5}$'

The first part of the regex will try the filenames having only 5 digits, and the second part is trying for filenames having 0-3 digits, 1 'h' or 'H' letter, 0 or 1 'oO' letter, 0 to 5 digits.

This regex works with awk too :

cat filename | awk  '/^[0-9]{5}$|^[0-9]{0,3}[hH]{1}[oO]{0,1}[0-9]{0,5}$/ {print}'
0
1

If you're not completely tied to awk, grep works well here:

$ grep -E '\<[[:digit:]]{1,3}HO?[[:digit:]]{1,5}\>' filename
123H7292
234HO7027

Is that the output you're looking for? I wonder if HO90902 should match.

The \< and \> are word boundaries, so "12345678H123" will not match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.