代码之家  ›  专栏  ›  技术社区  ›  deimus

Shell脚本:如何剪切字符串的一部分

  •  13
  • deimus  · 技术社区  · 15 年前

    我有以下字符串

    â   â³ eGalax Inc. USB TouchController          id=9    [slave  pointer  (2)]
    â   â³ eGalax Inc. USB TouchController          id=10   [slave  pointer  (2)]
    

    想得到身份证的名单吗?如何使用sed或其他方法实现这一点?

    6 回复  |  直到 11 年前
        1
  •  39
  •   Manoj Govindan    15 年前

    我将示例的内容粘贴到一个名为 so.txt

    $ cat so.txt | awk '{ print $7 }' | cut -f2 -d"="
    9
    10
    

    说明:

    1. cat so.txt 将文件的内容打印到 stdout .
    2. awk '{ print $7 }' 将打印第七列,即包含 id=n
    3. cut -f2 -d"=" 将使用 = 作为分隔符并获取第二列( -f2

    id= 另外,那么:

    $ cat so.txt | awk '{ print $7 }' 
    id=9
    id=10
    
        2
  •  3
  •   bluebrother    15 年前

    sed -e 's/.*id=\([0-9]\+\).*/\1/g'
    

    对每一行这样做,你就会得到ID列表。

        3
  •  2
  •   sid_com    15 年前

    perl解决方案:

    perl -nE 'say $1 if /id=(\d+)/' filename
    
        4
  •  2
  •   Dennis Williamson    15 年前

    你可以有 awk 不使用 cut :

    awk '{print substr($7,index($7,"=")+1)}' inputfile
    

    split() substr(index()) .

        5
  •  2
  •   ghostdog74    15 年前
    $ ruby -ne 'puts $_.scan(/id=(\d+)/)' file
    9
    10
    
        6
  •  1
  •   frayser    15 年前

    {Anything}id={ID}{space}{Anything} 
    {Anything}id={ID}{space}{Anything}
    

    --

    #! /bin/sh
    while read s; do
       rhs=${s##*id=}
       id=${rhs%% *}
       echo $id # Do what you will with $id here
    done <so.txt 
    

    或者总是第七场

    #! /bin/sh
    while read f1 f2 f3 f4 f5 f6 f7 rest
    do
    echo ${f7##id=}
    done <so.txt
    

    另请参见

    Shell Parameter Expansion

    推荐文章