我想为一个模式grep一个文件,但是显示该模式中没有的那一行的另一部分。
这是我的档案:
Function Process1 took [66] ms
Function Process2 took [1381] ms
Function Process1 took [1501] ms
Function Process2 took [41] ms
我想找到符合" Process2"的行。但只输出方括号中的时间。
所以我想要的输出是:
1381
41
答案 0 :(得分:1)
这些命令都有效......
grep Process2 file.txt | awk '{print $4}' | egrep -o '[^][]+'
grep Process2 file.txt | awk '{print $4}' | sed 's/[][]//g'
答案 1 :(得分:1)
grep -oP 'Process2.*\[\K[0-9]+'
-o
仅输出匹配的文本而不是整行
使用\K
erl模式时,-P
会转储与之匹配的字符。
$ echo """Function Process1 took [66] ms Function Process2 took [1381] ms Function Process1 took [1501] ms Function Process2 took [41] ms""" | grep -oP 'Process2.*\[\K[0-9]*' 1381 41
答案 2 :(得分:0)
我要告诉你的不是一个而是两个解决方案(略带细微差别):
选项1:识别[
和]
如果找到您的字段的密钥是[
和]
,您可以使用此代码:
grep Process2 infile | sed "s/.*\[//" | sed "s/].*//"
在这个例子中你......
sed
使用s
命令)"任何以[
&#34结尾的字符串; (由/.*[/
标识)并用#34替代;没有" (由//
确定。)sed
)"字符串]
后跟任何字符序列"并通过"没有"。选项2:提取第4个字段
如果你找到你的领域的关键是知道它在第4位,你可以提取它,然后用括号将其清除:
grep Process2 infile | cut --fields=4 --delimiter=" " | sed "s/\[//" | sed "s/\]//"
在这种情况下:
[41]
sed
更改了[
一无所知,而]
也没有更改。经过测试的会话
这是一个经过测试的会议:
xavi@guarra:~/tmp$ cat infile
Function Process1 took [66] ms
Function Process2 took [1381] ms
Function Process1 took [1501] ms
Function Process2 took [41] ms
xavi@guarra:~/tmp$ grep Process2 infile
Function Process2 took [1381] ms
Function Process2 took [41] ms
xavi@guarra:~/tmp$ grep Process2 infile | sed "s/.*\[//" | sed "s/].*//"
1381
41
xavi@guarra:~/tmp$ grep Process2 infile | cut --fields=4 --delimiter=" " | sed "s/\[//" | sed "s/\]//"
1381
41
xavi@guarra:~/tmp$
希望这有帮助!
答案 3 :(得分:0)
使用grep + sed:
public class Sum {
public static void main(String[] args) {
// TODO Auto-generated method stub
float sum = 0;
float numerator = 1;
int denominator = 1; //changed to int
for(int i = 1; i <= 10000000; i++)
{
sum = (numerator/(float)denominator) + sum; //this casts denominator to float
denominator++; //this will now increment integer
}
System.out.println("The sum is " + sum);
}
}