如何在第二列中打印第一个字符?

如何在第二列中打印第一个字符?

使用 egrep,如何打印姓氏以K或开头的所有行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+),直到字段结束 ( $)。

相关内容