简体   繁体   中英

Regex match strings in bash

I was curious if you can make regex to match 2nd character of a string with 2 from the back? For 1st and last its pretty easy and straightforward but i was curious if it can be done for any str length? I was playing with it in bash for the last hour and none of my solutions seams to work.

^(.).*\\1$ thats the regex I have for 1st and last char it probably needs too be a little edited for this but i have no idea how.

Can you help me with the other one?

examples:
abcsba - match as b(index 1) == b(index -2)
regex - match as e(index 1) == a(index -2)
abba - match 
unix - not matcha as indexOf(n) != indexOf(i)
linux - not match as indexOf(i) != indexOf(u)

Just discard equal number of character from the beginning and from the end:

$ pat='^.(.).*\1.$'
$ [[ abcsba =~ $pat ]] && echo yes || echo no
yes
$ [[ unix =~ $pat ]] && echo yes || echo no
no

or, generally use {n} (eg. to match 3rd character with 3rd from the end):

pat='^.{2}(.).*\1.{2}$'
$ [[ abcdef =~ $pat ]] && echo yes || echo no
no
$ [[ abccef =~ $pat ]] && echo yes || echo no
yes

In the second example we use single-character-ERE duplication operator {m,n} defined in POSIX for both basic and extended regular expressions (ERE variant is only relevant here though, since =~ operator in bash uses ERE). The {n} form is a special case, equal to {n,n} , meaning repeat the preceding character (or group) exactly n times.

As i understood you want to extract the characters . You can do it by awk command

echo "praveen" | awk '{print substr($1,1,2)}' pr 01HW497089:tmp Controller$

Here i am extracting column1 value from character 1 to character 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM