robera
robera

Reputation: 11

how to skip specific lines in awk and print the remaining

how can I read only lines: 3,9,12, 15 from the file containing the ff lines. The idea is whenever I get x and y , I wanted to print the last line among lines containing x and y. What I meant is , for example , if I have awk script like : BEGIN { name = $2; value=$3; } { if(name == x && value==y && the scan reaches at lines 3, 9, 12 and 15) printf("hello world") }. what expression can I use instead of "the scan reaches at lines 3, 9 12 and 15"

1 x y
2 x y 
3 x y 
4 a d
5 e f
6 x y
7 x y
8 x y
9 x y
10 g f
11 x y
12 x y
13 p r
14 w c
15 x y
16 a z

Upvotes: 1

Views: 3599

Answers (3)

9000492
9000492

Reputation: 13

You need to use two while loops here one to check the line and another to iterate. Something like this. Hope that helps

String line = ""; int i = 0;

    try {
        BufferedReader in = new BufferedReader(new FileReader("D:\\readline.txt"));
        while ((line = in.readLine()) != null) {
            i++;
            if (line.charAt(0) == 'x' && line.charAt(2) == 'y') {
                System.out.println("Line containg Y and Y");
                String searchline = line;
                while ((line = in.readLine()) != null) {   //Iterate untill you find the last line of X and Y
                    i++;         //To keep count of the line read
                    if (line.charAt(0) == 'x' && line.charAt(2) == 'y') {
                        searchline = line;
                        continue;
                    } else {
                        break;
                    }

                }

                System.out.println("Printing the  line ::" + (i - 1) + ":: containing X and Y::::::::" + searchline);
            }
        }

    } catch (Exception e) {
        System.out.println("Exception Caught::::");
    }
}

Upvotes: -2

Chris Seymour
Chris Seymour

Reputation: 85775

One way with awk:

$ awk '/^[0-9]+ x y$/{a=$0;f=1;next}f{print a;f=0}' file
3 x y
9 x y
12 x y
15 x y

One way without awk:

$ tac file | uniq -f1 | fgrep -w 'x y' | tac
3 x y
9 x y
12 x y
15 x y

Upvotes: 3

Jotne
Jotne

Reputation: 41446

Some like this?

awk 'a=="xy" && $2$3!="xy" {print b} {a=$2$3;b=$0}' file
3 x y
9 x y
12 x y
15 x y

Upvotes: 1

Related Questions