如何egrep第二列中的第一個字元?

如何egrep第二列中的第一個字元?

使用egrep,如何列印姓氏以Kor開頭的所有行k

Jennifer Cowan:548-834-2348:583 Laurel Ave., Kingsville, TX 83745:10/1/35:58900
Lesley Kirstin:408-456-1234:4 Harvard Square, Boston, MA 02133:4/22/62:52600
Jennifer Cowan:548-834-2348:583 Laurel Ave., kingsville, TX 83745:10/1/35:58900
Lesley kirstin:408-456-1234:4 Harvard Square, Boston, MA 02133:4/22/62:52600
William Kopf:846-836-2837:6937 Ware Road, Milton, PA 93756:9/21/46:43500
Arthur Putie:923-835-8745:23 Wimp Lane, Kensington, DL 38758:8/31/69:126000

答案1

第一次嘗試是

  grep '^[^ ]*  *[Kk]'

但這假設總是只有一個名字並且沒有首字母縮寫。
在此範例中,您可以使用該-i選項並將其替換[Kk]k

抓住第一個冒號可能會更好

  grep -i ' k[^:]*:'

如果您確實只想列印姓氏,而不是整行,則應考慮使用 awk (或 perl)


更新:這是第一個 grep 表達式'^[^ ]* *[Kk]'的建構方式

  '     apostrophe delimits a parameter that contains spaces
        and other so-called meta-characters that the shell might alter
  ^     caret means start of line
  [     brackets mark a set of characters, any one of which is to be matched
  ^     inside brackets means negation or 'none of the following'
        so `[^ ]` means "not a space"
  ]     is the end of the set.
  *     means 0,1 or more of the prior character
        so `[^ ]*` means any contiguous group of characters that does not 
        contain a space
  then we have two spaces
  *     means 0,1 or more of the prior character
        so space space * means 1 nor more spaces.
  [Kk]  means `K` or `k`
  [^:]* means 0,1 or more characters that are not a colon
  :     followed by a colon

答案2

perl -aF/:/ -ne 'print if $F[0] =~ /\s[Kk]\S+$/'
  • 使用-aF/:/,整行被分成以冒號分隔的欄位;
  • $F[0]是第零個欄位並包含名稱;
  • /\s[Kk]\S+$/匹配空格 ( \s),後面接著Kk,後面跟著任意數量的非空格字元 ( \S+),直到欄位末端 ( $)。

相關內容