1

I have these 200+ character long strings stored in a file. In each string, there exists a pattern such as ##XXX###XXXX where # is a digit between 0 and 9 and X is a character between A and Z in upper or lower case. Leading and trailing characters can be any printable character, including space, but other than [0-9], [a-z] and [A-Z]. And the length of this string is not fixed either, but no less than 180 characters, mostly more than 200.

All I need is the start location of the pattern in the longer string, like what index function in perl returns. My caveat is there is no perl on this system with no additional software installation chance.

So far what I was able to think is to start from the 1st char of the string and check if the character I get is a digit. If yes, check the second one for being a digit. So far and so on... repeat until all 12 characters are satisfied, by using cascaded if statements, and breaking out of the loop if the condition in the comparison chain returns an unsatisfactory character before we hit the count of 12.

I was wondering if there is anything can be done with regex or without, eliminating the need for 12 cascaded if statements under bash. And yes I have access to sed and awk if either will make life easier.

  • You want the start location of the pattern in every string? – Kira Jan 6 '16 at 22:07
0

Awk has a match function that does something that sounds like what you want

awk '{ print match($0, /[0-9][0-0]rest_of_your_pattern/) }' your_file

If no match is found then match returns 0 (and printed).

  • The pattern is /[0-9][0-9][a-zA-Z][A-Za-z][A-Za-z][0-9][0-9][0-9]/ – Kira Jan 6 '16 at 22:11
1
< your_file \
tr -c \[:alnum:] '[\n*]' |
grep -n ............

...probably? strings is also pretty handy w/ that...

< your_file \
tr -c \[:alnum:] '[\0*]' |
strings -n12 -td
1

No external tool called (faster?):

while IFS= read -r a; do
    head=${a%%[[:alnum:]]*}
    tail=${a##*[[:alnum:]]}
    a=${a##"$head"}
    b=${a%%"$tail"}
    printf '%4d <%s>\n' "${#head}" "$b"
done < file.csv

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.