使用bash从文件中提取文本 [英] Extracting text from file using bash

查看:110
本文介绍了使用bash从文件中提取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Linux的新手,并且有一个非常大的文本日志文件可供提取.我想用bash吗?

I am new to Linux and have a very large text log file from which to extract. I thought to use 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,但还没有弄清楚.帮助非常感谢.

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.

示例输出如下:

xyz Trusted certif ok
abc Trusted certif ok
dbf Trusted certif not ok

推荐答案

尝试执行此操作:

awk -F: '/^Node/{v=$2}/^INFO/{print v $2}' file.txt

的问题:

while IFS=: read -r c1 c2; do
    [[ $c1 == Node ]] && var=$c1
    [[ $c1 == INFO ]] && echo "$var$c2"
done < file.txt

的问题:

perl -F: -lane '
    $v = $F[1] if $F[0] eq "Node";
    print $v, $F[1] if $F[0] eq "INFO"
' file.txt

的问题(在文件中,用法:./script.py file.txt):

in python (in a file, Usage : ./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

这篇关于使用bash从文件中提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆