問題描述
grep 如何匹配一些字母或行尾 (grep how to match some letters OR end of line)
I have some files with lines like this:
vi
vi‑sw600dp
ddnki
xhdpi
I want to use grep to match only lines where are two letters at start of line and after that letters are dash OR nothing(new line).
So output will be like this:
vi
vi‑sw600dp
I try something like this:
grep '^[A‑Za‑z]\{2\}[‑\n]'
I expect, it match lines with two starting letters a‑z,A‑Z and then with dash or new line. But it doesn't work. \n was not assumed new line but characters so it otuput this:
vi
vi‑sw600dp
ddnki
Can you please help me? Thanks.
‑‑‑‑‑
參考解法
方法 1:
You are close. You need to use the end‑of‑line anchor $
instead of \n
. $
cannot be part of a character group, so you should use an atom grouping instead:
grep '^[A‑Za‑z]\{2\}\(‑\|$\)'
Or with ‑E
:
grep ‑E '^[A‑Za‑z]{2}(‑|$)'