【发布时间】:2016-04-01 05:50:35
【问题描述】:
假设我有以下字符串:
mystring="something something something schwifty3 something"
现在我知道 schwifty 后面有一个数字,但我想要这个字符串中的整个单词,不包括其他所有内容。
grep -o 由于某种原因似乎不起作用,甚至不是一个可用的选项......有什么想法吗?
【问题讨论】:
假设我有以下字符串:
mystring="something something something schwifty3 something"
现在我知道 schwifty 后面有一个数字,但我想要这个字符串中的整个单词,不包括其他所有内容。
grep -o 由于某种原因似乎不起作用,甚至不是一个可用的选项......有什么想法吗?
【问题讨论】:
将空格转换为换行符,以便 grep 仅返回单个单词。
mystring="something something something schwifty3 something"
echo "$mystring" | tr " " '\n' | grep "schwifty"
【讨论】:
怎么样
grep -Po "schwifty\d" <<< $mystring
如果字符串中可能有多个数字,则为:
grep -Po "schwifty\d+" <<< $mystring
【讨论】:
对于纯 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 内置函数和机制,没有外部命令。
【讨论】:
-w 用于 grep 中的单词
echo sth sth something sth1|sed 's/ /\n/g'|grep -w sth
sth
sth
【讨论】:
$ 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
【讨论】:
你也可以在 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"
【讨论】: