1

I am trying to take a text file called 'input', of the form

line1 
line2
line3
PATTERN
x y z
x y z
lineN

and use awk to place a number (1) after each "x y z" line. I need the lines before the PATTERN and after the "x y z' lines (lineN) in the output. The output I needs looks like this:

line1
line2
line3
PATTERN
x y z   1 
x y z   1
lineN

What I have so far is:

awk '/PATTERN/ {getline; print $0 "   1" }' < input > output 

This gives:

x y z   1

Is it possible to set up a loop to get awk to append an arbitrary number of "x y z" lines or stop after the "x y z" type lines finish?

2
  • I edited to look more file like. do you need remplacement after PATTERN (and x y z might be 1 2 3 or foo what ever) or editing only line with x y z ? Commented Mar 4, 2015 at 11:09
  • Thank you, I didn't know how to represent it in the fashion you have changed it to. Yes replacement after the PATTERN is found. x y z are just three columns only the lines with x y z should be appended if possible. Commented Mar 4, 2015 at 11:13

2 Answers 2

1

The looping can help:

awk '/PATTERN/{print;getline;while(!/lineN/){$(NF+1)="  1";print;getline}}1'

Or to extend @Janis idea:

awk '/lineN/{f=0}f{$(NF+1)="  1"}/PATTERN/{f=1}1'
0
1

You are saying that only the literal "x y z" lines after PATTERN shall be replaced.

awk '
  /PATTERN/ { f=1 }
  f && /x y z/ { print $0, 1 ; next }
  { print }
'

If it's lines with three arbitrary fields then use

awk '
  /PATTERN/ { f=1 }
  f && NF==3 { print $0, 1 ; next }
  { print }
'
4
  • If OP wants to print lines after PATTERN and before lineN (as one block) you have to add f=0 after block finish. Commented Mar 4, 2015 at 11:38
  • Costas, the OP's sample as presented did not suggest that lineN is a pattern like "PATTERN" that terminates a block; as described it's just a continuation of the data line1, line2, ..., lineN, or so it seems at least. Commented Mar 4, 2015 at 11:42
  • lineN can have 3 fields too... In any way OP should some how indicate difference between x y z and lineN to fix position where script should stop to add 1 Commented Mar 4, 2015 at 11:51
  • Indeed the actual requirements would need clarification. I'm sure the OP will come back to ask if necessary once he switches from his sample data to the real data. Commented Mar 4, 2015 at 11:55

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.