Help in understanding awk expression

Hi,
Could somebody help me in understanding the following awk expression:

awk -v n="POINT" '/%/{print $0 "\n" n ;next}1' < file name

Thanks,
Arun

# Before the program is run, set the variable n to the value "POINT"
-v n="POINT"

# For every line containing % somewhere:
'/%/ {
        # Print the entire line, followed by a newline, followed by "POINT"
        print $0 "\n" n
        # Skip this line so the '1' below doesn't print it
        next
# The '1' after the code block tells it to print every single line.
# It could be an expression too.
} 1' < file name

But I would've just written it as:

awk -v n="POINT" '/%/ { $0=$0"\n" n } 1'

To avoid the 'print' and the 'next'. For any line matching %, it just changes the current line( $0 ) to add "\nPOINT" to the end, so the print-every-line statement prints correctly in both cases.

1 Like

Hi Corona,

Thanks for the explanation. Could you please tell me how to change this code to replace the % to POINT only for the particular in specific the 3rd occurrence and come out immediately without replacing the other entries in the same file.

Thanks a lot in advance :slight_smile:

Arun

I don't perfectly understand what you want. Could you show an example of the input you have, and an example of the output you want?

I have a file like this:
%
10
%
NAME_1
NAME_2
NAME_3
NAME_4
%
LOCAL
%
02/02/12
%
08:00:00
%
YES
%

Where I need to change the value of LOCAL to POINT. Since the value of LOCAL is dynamic (it can assume any text), I thought of using % as the separator. It should change the value of text that is after the 3rd occurrence of % . So the output should be like:

%
10
%
NAME_1
NAME_2
NAME_3
NAME_4
%
POINT
%
02/02/12
%
08:00:00
%
YES
%

Your help is much appreciated.

Thanks,
Arun

you can assign the dynamic value in n like,

awk -v n="$dynamicval" 'BEGIN{i=0;}/^%$/{i++}$0 !~ /^%$/{if(i == 3 ){gsub(n,"POINT")print $0;}' < file name

Cheers,
Ranga:)

$ nawk -v n="LOCAL" 'gsub(n,"POINT",$0)1' input.txt 
%
10
%
NAME_1
NAME_2
NAME_3
NAME_4
%
POINT
%
02/02/12
%
08:00:00
%
YES
%