Searching for a substring in a string in shell script
本问题已经有最佳答案,请猛点这里访问。
我有一根很长的绳子(长度也不固定)我想提取"email"和"@gmail.com"之间的子字符串
假设是
1  | xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc  | 
我想提取字符串中的"子字符串"。我可以使用正则表达式和sed工具来完成这项工作吗?
1  | perl -lne 'print $1 if(/email:(.*?)\@gmail.com/)'  | 
下面的测试:
1 2 3  | > echo"xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc" | perl -lne 'print $1 if(/email:(.*?)\@gmail.com/)' substring >  | 
壳可以处理这个:
1 2 3 4 5  | $ line='xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc' $ name=${line#*email:} # remove the prefix ending with"email:" $ name=${name%@gmail.com*} # remove the suffix starting with"@gmail.com" $ echo $name substring  | 
   另一个
1 2  | awk -F":" '{split($2,a,"@");print a[1]}' file substring  | 
你有很多的网络搜索公司两个Gmail地址
1 2  | awk -F":" '/gmail\.com/ {split($2,a,"@");print a[1]}' substring  | 
   利用
1 2 3  | INPUT="xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc" USERNAME=$(sed -n"s/.*\email:\(.*\)@gmail\.com.*/\\1/p" <<< $INPUT) echo $USERNAME  | 
VALUE="xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc"
echo $VALUE | awk -F":" '{print $2}' |cut -d@ -f1
我认为grep(正面和积极的预测和追溯)是正确的工具的工作:
1 2  | $ grep -oP '(?<=email:).*?(?=@gmail\.com)'<<<"xhxjcndjcnkjcnd cjkjcdckjncx email:[email protected] djc" substring  |