提取字符之间的数字 - grep [英] extract number between characters - grep
问题描述
我正在使用PHP,并希望使用grep提取字符'gi |这里是数字|'
,并将它分配给变量。
I am using PHP and want to extract numbers between characters 'gi|HERE IS THE NUMBER|'
using grep and assign it to variable.
该文件包含:
The file contains:
>gi|1786181|gb|AE000111|ECAE000111 Escherichia coli , thrL, thrA, thrB, thrC, yaaA, yaaJ, talB, mog, yaaH genes from bases 1 to 10596
>gi|1786192|gb|AE000112|ECAE000112 Escherichia coli , htgA, yaaI, dnaK, dnaJ, yi81_1, yi82_1
我想在此处提取数字: gi | 1786181 |
和 gi | 1786192 |
并将它们放入x和y变量中。
I want to extract the number here: gi|1786181|
and gi|1786192|
and put them in x and y variables.
,输出将是: x = 1786181
, y = 1786192
我试试:
I try:
$x = shell_exec("C:\\cygwin64\\bin\\bash.exe --login -c \" grep -o 'gi\|[0-9]\|' $file.txt > $result.txt 2>&1\"");
没有用。
有什么帮助吗?
It did not work. Any help please?
推荐答案
为什么要使用 grep
贝壳?使用 preg_match():
Why use grep
through the shell? Use preg_match():
$input = file_get_contents('file.txt');
preg_match("/gi\|([0-9]+)\|/", $input, $matches);
$ matches
会返回如下所示的内容,数组中的第一项包含完整匹配,第二项仅包含您之后的值:
$matches
would return something like the following, the first item in the array contains the full match, the second just the values that you're after:
array(
0 => array(
"gi|1786181|",
"gi|1786192|"
),
1 => array(
"1786181",
"1786192"
)
)
无论哪种情况,您都需要指定您需要一个或多个整数:
In either case, you'll need to specify that you require one or more integers:
gi\|([0-9]+)\|
这篇关于提取字符之间的数字 - grep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!