bash 使用bash从文件中提取文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14204946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extracting text from file using bash
提问by Allen
I am new to Linux and have a very large text log file from which to extract. I thought to use bash?
我是 Linux 新手,有一个非常大的文本日志文件可以从中提取。我想用 bash 吗?
For example, the file contains:
例如,该文件包含:
Node:xyz
Time:01/07/13 14:26:17
INFO: Trusted certif ok
Node:abc
Time:01/07/13 14:26:18
INFO: Trusted certif ok
Node:def
Time:01/07/13 14:26:18
INFO: Trusted certif not ok
I need to extract the text after Node: and add it to the text after Info: to display on one line, output to be redirected to a new file. I am trying awk and sed, but not figured it out yet. Help much appreciated.
我需要提取 Node: 之后的文本,并将其添加到 Info: 之后的文本中以显示在一行上,输出将被重定向到一个新文件。我正在尝试 awk 和 sed,但还没有弄清楚。非常感谢帮助。
Example output would look like:
示例输出如下所示:
xyz Trusted certif ok
abc Trusted certif ok
dbf Trusted certif not ok
回答by Gilles Quenot
Try doing this :
尝试这样做:
in awk
在awk
awk -F: '/^Node/{v=}/^INFO/{print v }' file.txt
in bash:
在bash 中:
while IFS=: read -r c1 c2; do
[[ $c1 == Node ]] && var=$c1
[[ $c1 == INFO ]] && echo "$var$c2"
done < file.txt
in perl:
在perl 中:
perl -F: -lane '
$v = $F[1] if $F[0] eq "Node";
print $v, $F[1] if $F[0] eq "INFO"
' file.txt
in python(in a file, Usage : ./script.py file.txt):
在python中(在一个文件中,用法:)./script.py file.txt:
import sys
file = open(sys.argv[1])
while 1:
line = file.readline()
tpl = line.split(":")
if tpl[0] == "Node":
var = tpl[0]
if tpl[0] == "INFO":
print var, tpl[1]
if not line:
break
回答by perreal
Using sed:
使用 sed:
sed -n '/^Node/N;/Time/N;s/^Node:\([^\n]*\)\n[^\n]*\n[^ ]* / /p' input
回答by Vijay
perl -F: -lane '$x=$F[1] if(/^Node:/);if(/^INFO:/){print "$x".$F[1];}' your_file
tested below:
测试如下:
> cat temp
Node:xyz
Time:01/07/13 14:26:17
INFO: Trusted certif ok
Node:abc
Time:01/07/13 14:26:18
INFO: Trusted certif ok
Node:def
Time:01/07/13 14:26:18
INFO: Trusted certif not ok
> perl -F: -lane '$x=$F[1] if(/^Node:/);if(/^INFO:/){print "$x".$F[1];}' temp
xyz Trusted certif ok
abc Trusted certif ok
def Trusted certif not ok
回答by Sidharth C. Nadhan
sed -n 'N;N;s/\n.*\n/ /;s/\S*://g;p;n' file

