tres.14159
tres.14159

Reputation: 920

How to iterate each group several lines from text file?

I have a text file more or less:

log_file.txt

#Date: 2018-01-01 11:12:33
value1:aaa
value2:bbb

#Date: 2018-01-03 11:12:33
value1:aaa
value2:ccc

#Date: 2017-05-12 22:12:33
value1:ddd
value2:aaa

I look for a bash script something as:

#!/usr/bin/env bash

for group_lines in $(<something log_file.txt init_match("#.*") end_match("\n")>)
do
  value1=$(echo -e "$group_lines"  | head -1 | sed 's/value1://g')
  value2=$(echo -e "$group_lines"  | head -2 | tail -1 | sed 's/value2://g')

  <do something value1 and value2>
done

I think that it is with some awk code.

Upvotes: 0

Views: 80

Answers (2)

tres.14159
tres.14159

Reputation: 920

I found it. The script is:

#!/usr/bin/env bash

for line in $(cat log_file.txt | awk '/#/{flag=1;next; print line; line=""} /^$/{flag=0; line=""} {if (flag == 1) { if (length(line) == 0) {line=$0} else {line=line"|#@#|"$0}}} END{if (flag == 1) {print line}}')
do
  value1=$(echo $line | awk -F"[|]#@#[|]" '{print $1}')
  value2=$(echo $line | awk -F"[|]#@#[|]" '{print $2}')

  <do something value1 and value2>
done

Upvotes: 0

Paul Hodges
Paul Hodges

Reputation: 15273

If your format is that consistent, you can just read the file and take action based on what you read. Don't spawn a bunch of unnecessary processes.

$: while IFS=: read key val
> do case $key in
>    value1) value1=$val;;
>    value2) value2=$val
>            echo "<do something value1 and value2>: $value1 $value2";;
>    esac
> done < log_file.txt
<do something value1 and value2>: aaa bbb
<do something value1 and value2>: aaa ccc
<do something value1 and value2>: ddd aaa

Upvotes: 1

Related Questions