Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting text from file using bash

Tags:

bash

sed

awk

I am new to Linux and have a very large text log file from which to extract. I thought to use 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.

Example output would look like:

xyz Trusted certif ok
abc Trusted certif ok
dbf Trusted certif not ok
like image 716
Allen Avatar asked Sep 16 '25 07:09

Allen


1 Answers

Try doing this :

in awk

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

in bash :

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

in 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 ):

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
like image 113
Gilles Quenot Avatar answered Sep 17 '25 21:09

Gilles Quenot