[英]Extracting text from file using bash
我是Linux的新手,並且有一個非常大的文本日志文件可從中提取。 我想用bash嗎?
例如,文件包含:
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
我需要在Node:之后提取文本,並將其添加到Info:之后的文本中,以顯示在一行上,然后將輸出重定向到新文件。 我正在嘗試awk和sed,但還沒有弄清楚。 幫助非常感謝。
輸出示例如下:
xyz Trusted certif ok
abc Trusted certif ok
dbf Trusted certif not ok
嘗試這樣做:
在awk中
awk -F: '/^Node/{v=$2}/^INFO/{print v $2}' file.txt
在bash中 :
while IFS=: read -r c1 c2; do
[[ $c1 == Node ]] && var=$c1
[[ $c1 == INFO ]] && echo "$var$c2"
done < file.txt
在perl中 :
perl -F: -lane '
$v = $F[1] if $F[0] eq "Node";
print $v, $F[1] if $F[0] eq "INFO"
' 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
使用sed:
sed -n '/^Node/N;/Time/N;s/^Node:\([^\n]*\)\n[^\n]*\n[^ ]* /\1 /p' input
perl -F: -lane '$x=$F[1] if(/^Node:/);if(/^INFO:/){print "$x".$F[1];}' your_file
測試如下:
> 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
sed -n 'N;N;s/\n.*\n/ /;s/\S*://g;p;n' file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.