Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am looking to search a file for a column that is 3 letters followed by any 3 or 4 numerals. eg.
if ( $1 ~ /^[A-Z][A-Z][A-Z][0-9][0-9][0-9]/)
However I need the 3 letters to be a variable, so I am looking for the result of SP="ABC" if ( $1 ~ /^/SP/[0-9][0-9][0-9]/)
This however does not work, and I've not found a way to combine a variable and regular expression in the search pattern. Any help greatly appreciated.

share|improve this question
SP="ABC" 
if ( $1 ~ "^" SP "[0-9]{3}")

(note that SP's content is still treated as a regexp, if that's not wanted:

if (index($1, SP) == 1 && substr($1, length(SP)+1) ~ /^[0-9]{3}/)

)

share|improve this answer

You can tell awk to read regular expression starting with exact chars, and then with a charater "type" in square brackets, followed by repetition number in curly brackets. Like so:

echo "ABC956" |  awk '{ if( $1 ~ /^ABC[0-9]{3}/) print "HELLOWORLD" }'                                 
HELLOWORLD

You could use logical operator && to test for presence of both variable and the regular expression as well

echo "ABC956" |  awk -v VAR="ABC" '{ if( $1 ~ VAR && $1 ~ /[0-9]{3}/) print "HELLOWORLD" }'            
HELLOWORLD
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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