0

I have file1 which looks like this:

0 0
0 1
0 8
ST1 2 3
5 2
2 2
ST3 4 3
4 2
5 5
ST5 1 9
1 5
7 8

Desired output file:

ST1 6 5 2
ST3 12 4 5
ST5 9 1 7

How to solve this? I would like to use awk. I don't know how to write the algorithm so that I can process the lines to look as in the desired output.

The idea is that I want to find the pattern (ST) and start processing from that point.

The output file scheme: ST*, column2 multiplied by column 3 on the row where we have "ST", column 1 from the rows below the "ST", but only until the next "ST" appearance.

I also don't want to process anything before the first ST*.

1
  • You have some answers, mine included, assuming there's always 2 lines following the ST line - is that an accurate assumption? If not, please update your question to show varying numbers of lines per record.
    – Ed Morton
    Commented Mar 2, 2022 at 13:25

4 Answers 4

3

With any awk:

$ awk '/^ST/{c=1} c{ printf "%s", (c++==1? ors $1 OFS $2*$3: OFS $1); ors=ORS } 
  END{ print "" }' infile
ST1 6 5 2
ST3 12 4 5
ST5 9 1 7
0
1

Assuming every row has 2 numbers, you can set the record separator (RS) to "ST":

awk '
  BEGIN{RS="ST"}
  NR>1 {print RS $1, $2*$3, $4, $6}
' file

Output:

ST1 6 5 2
ST3 12 4 5
ST5 9 1 7

Note: Requires GNU awk.

0
0

One way to approach this pbm is

awk -v ORS= '
($1 ~ /^ST[0-9]/) && (NF > 2) {
  if (f++) print RS
  print $1, $2*$3
  next
}
f {print "", $1}
END {print RS}
' file

Output:

ST1 6 5 2
ST3 12 4 5
ST5 9 1 7
0

With GNU awk for multi-char RS and RT and assuming there's always 3 rows to each record as showing in the sample input:

$ awk -v RS='ST([^\n]+\n){3}' '{$0=RT; print $1, $2*$3, $4, $6}' file
ST1 6 5 2
ST3 12 4 5
ST5 9 1 7

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .