0

I wish to grep a line staring which start with Alphabet followed by 5 numbers.

MY approach is eg

'A12345'
'A123456'


output should be only line starting with Alphabet followed by 5 numbers 

ie 'A12345'

 My approach : it doesn't work 
 grep -E '[A-Z]''[0-9]{5}'
yamut
  • 135
  • 1
  • 8

1 Answers1

1
# PCRE allows \xHH escapes
$ grep -P '^\x27[A-Z][0-9]{5}\x27' ip.txt
'A12345'

# double quotes can also be used here since there's no clash
$ grep -E "^'[A-Z][0-9]{5}'" ip.txt
'A12345'

# this is same as ^' followed by [A-Z][0-9]{5} and then another '
$ grep -E "^'"'[A-Z][0-9]{5}'"'" ip.txt
'A12345'

Here's an example where double quotes can be problematic. See https://mywiki.wooledge.org/Quotes and Difference between single and double quotes in Bash for more details.

$ echo '1a$(z)b' | grep -E "a$(z)b"
z: command not found
Sundeep
  • 23,246
  • 2
  • 28
  • 103
  • Thank you Sandeep , incase if I have two string , each is inside a single quote in a line . It doesn't grep anything . Can you please tell me what that reason could be ... eg in a line if I have such string 'A12345' 'A12345' – yamut Jun 10 '21 at 14:40
  • I can't guess what could fail unless you show the exact commands you tried. And I don't know what kind of variations in input you can have. It is better to ask a new question and use code formatting properly which is difficult to do in comments. – Sundeep Jun 10 '21 at 14:50
  • 1
    @yamut - Add `o` flag then: `grep -Eo '[A-Z][0-9]{5}'` – Darkman Jun 10 '21 at 14:53
  • @Sundeep I have created a new question , can you please have a look at it. https://stackoverflow.com/questions/67926274/how-to-grep-a-line-containing-a-string-enclosed-in-single-quote – yamut Jun 10 '21 at 17:57