2013-09-30 92 views
0

如何從包含ff行的文件中只讀取行:3,9,12,15。 這個想法是每當我得到x和y時,我想在包含x和y的行之間打印最後一行。 我的意思是,例如,如果我有awk腳本,如:BEGIN {name = $ 2;值= $ 3; printf(「hello world」)} {if(name == x & & value == y & &掃描到達第3,9,12和15行)printf(「hello world」)}。我可以用什麼表達來代替「掃描到達第3,9,12和15行」如何跳過awk中的特定行並打印剩餘的

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 
+0

第2行和第3行在您的輸入中有尾隨空格這是真的嗎? –

回答

1

有些這樣的?與awk

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 
+0

這工作正常,它的東西我要在awk腳本內部使用,而不是在命令行上... – robera

+0

沒問題,這在shell腳本中正常工作。然後,您可以將輸出重定向到文件或變量。文件:'awk'a ==「xy」&& $ 2 $ 3!=「xy」{print b} {a = $ 2 $ 3; b = $ 0}'file> result'或者變量:'result = $(awk'a = =「xy」&& $ 2 $ 3!=「xy」{print b} {a = $ 2 $ 3; b = $ 0}'file)' – Jotne

+0

但是有沒有一種方法可以將它用作條件,即if($ 2 = = x && $ 3 == y)&&掃描到達第3,9,12和15行,打印「sth else」,而不是行本身 – robera

2

方式一:

$ 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 

的一種方式,而不awk

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

嗯,'awk'給我行1,9,12,15。它似乎是正確的完成,所以不知道什麼是錯的。我的'awk'給出了正確的行。編輯:'tac'給了我1,3,9,12,15,所以它也有一些錯誤。我確實使用了Ubuntu 12.04 – Jotne

+0

你的文件中有空白符號,試試'cat -E file'。我對空白更加嚴格,對於OP來說可能有用也可能沒有用http://edone.com/puI2Ss –

+0

是的,羅伯拉斯帖子中的第2行和第3行有空格,刪除它們就行了。由於使用'$ 2 $ 3',我沒有在我的解決方案中看到這個。如果您的解決方案可能已經寫入'awk'$ 2 $ 3 ==「xy」{a = $ 0; f = 1; next} f {print a; f = 0}''對空間更加健壯。 – Jotne

-1

這裏需要使用兩個while循環一個檢查線路和另一迭代。像這樣的東西。希望有幫助

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::::"); 
    } 
}