【问题标题】:In UNIX, how could you find a single word in a long string?在 UNIX 中,如何在长字符串中找到单个单词?
【发布时间】:2016-04-01 05:50:35
【问题描述】:

假设我有以下字符串:

 mystring="something something something schwifty3 something"

现在我知道 schwifty 后面有一个数字,但我想要这个字符串中的整个单词,不包括其他所有内容。

grep -o 由于某种原因似乎不起作用,甚至不是一个可用的选项......有什么想法吗?

【问题讨论】:

    标签: string unix awk grep word


    【解决方案1】:

    将空格转换为换行符,以便 grep 仅返回单个单词。

    mystring="something something something schwifty3 something"
    echo "$mystring" | tr " " '\n' | grep "schwifty"
    

    【讨论】:

    • 我将永远使用它。谢谢你,这是完美的!
    【解决方案2】:

    怎么样

    grep -Po "schwifty\d" <<< $mystring
    

    如果字符串中可能有多个数字,则为:

    grep -Po "schwifty\d+" <<< $mystring
    

    【讨论】:

      【解决方案3】:

      对于纯 shell 方法,删除前缀 (#) 和后缀 (%) 的字符串替换将起作用:

      mystring="something something something schwifty3 something"
      
      s=schwifty
      
      case $mystring in 
      (*$s*) 
          a="$s${mystring#*$s}"
          echo ${a%% *}
      esac
      

      这将显示任何以$s 开头的字符串在$mystring 中的第一次出现。假设:您仅在 ascii 空间上拆分字符串。

      纯 shell 方法意味着我们只使用 shell 内置函数和机制,没有外部命令。

      【讨论】:

        【解决方案4】:

        -w 用于 grep 中的单词

        echo sth sth something sth1|sed 's/ /\n/g'|grep -w sth
        sth
        sth
        

        【讨论】:

          【解决方案5】:
          $ echo $mystring
          something something something schwifty3 something
          
          $ echo $mystring | sed -n 's/.*\s*\(schwifty[0-9]\)\s*.*/\1/p'
          schwifty3
          
          $ echo $mystring | sed -n 's/.*\s*\(schwifty\)[0-9]\s*.*/\1/p'
          schwifty
          

          【讨论】:

            【解决方案6】:

            你也可以在 bash 中做到这一点。

            a=" $mystring "      # pad with spaces (in-case the word is first or last)
            a="${a#* schwifty}"  # chop all before and including schwifty
            a="schwifty${a%% *}" # restore schwifty chop all after first word, 
            echo "$a"
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-07-07
              • 2019-08-26
              • 2016-05-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-02-22
              相关资源
              最近更新 更多