【问题标题】:Substring from a file来自文件的子字符串
【发布时间】:2013-01-01 05:08:22
【问题描述】:

我需要使用正则表达式从文件中提取重合线:

这是文件的内容:

netbios-ns      137/tcp                         # NETBIOS Name Service
netbios-ns      137/udp
hkp             11371/tcp                       # OpenPGP HTTP Keyserver
hkp             11371/udp                       # OpenPGP HTTP Keyserver
bprd            13720/tcp                       # VERITAS NetBackup
bprd            13720/udp
vopied          13783/udp

我需要使用137grep 进行过滤:

grep -n -e "137" file

输出必须是:

netbios-ns      137/tcp                         # NETBIOS Name Service
netbios-ns      137/udp

【问题讨论】:

  • fgrep " 137/" services.txt
  • 这与这个问题无关。只需提一下,如果您想检查哪个程序/进程正在使用哪个端口,/etc/services 文件有时会误导您。请改用lsof

标签: linux string shell grep


【解决方案1】:

如果你总是有前面的空格和一个斜杠,那么:

$ grep " 137/" file
netbios-ns 137/tcp # NETBIOS Name Service
netbios-ns 137/udp

或者更健壮,检查两边的非数字:

$ grep "[^[:digit:]]137[^[:digit:]]" file
netbios-ns 137/tcp # NETBIOS Name Service
netbios-ns 137/udp

【讨论】:

  • 甚至grep -w 137 /etc/services。让grep 为您包装词边界逻辑...
【解决方案2】:

使用 grep 的单词边界:grep '\<137\>' file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多