簡體   English   中英

使用awk腳本在兩個模式之間拉文本

[英]pulling text between two patterns with awk script

輸入文字檔:

This is a simple test file.
#BEGIN
These lines should be extracted by our script.

Everything here will be copied.
#END
That should be all.
#BEGIN
Nothing from here.
#END

所需的輸出:

These lines should be extracted by our script.

Everything here will be copied.

我的awk腳本是:

#!/usr/bin/awk -f
$1 ~ /#BEGIN/{a=1;next};a;$1 ~ /#END/ {exit}

我當前的輸出是:

These lines should be extracted by our script.

Everything here will be copied.
#END

我唯一的問題是我仍在打印“ #END”。 我已經嘗試了很長時間以某種方式消除這種情況。 不知道該怎么做。

在我們注釋腳本中的每個命令時,IMO變得很明顯。 腳本可以這樣寫:

#!/usr/bin/awk -f
$1 ~ /#BEGIN/ { # If we match the BEGIN line
  a=1           # Set a flag to one
  next          # skip to the next line
}
a != 0 {        # if the flag is not zero
  print $0      # print the current line
}
$1 ~ /#END/ {   # if we match the END line
  exit          # exit the process 
}

請注意,我將a擴展為等效形式a!=0{print $0} ,以使觀點更清楚。

因此,當設置了標志時,腳本開始打印每行,當到達END行時,它已經在退出前打印了該行。 由於您不希望打印END行,因此應在打印該行之前退出。 因此,腳本應變為:

#!/usr/bin/awk -f
$1 ~ /#BEGIN/ { # If we match the BEGIN line
  a=1           # Set a flag to one
  next          # skip to the next line
}
$1 ~ /#END/ {   # if we match the END line
  exit          # exit the process 
}
a != 0 {        # if the flag is not zero
  print $0      # print the current line
}

在這種情況下,我們在打印行之前退出。 可以簡寫形式寫成:

awk '$1~/#BEGIN/{a=1;next}$1~/#END/{exit}a' file

或更短

awk '$1~/#END/{exit}a;$1~/#BEGIN/{a=1}' file

關於注釋中提出的其他約束,為避免跳過要打印的塊中的任何BEGIN塊,我們應該刪除next一條語句,並像上面的示例一樣重新排列行。 以擴展的形式是這樣的:

#!/usr/bin/awk -f
$1 ~ /#END/ {   # if we match the END line
  exit          # exit the process 
}
a != 0 {        # if the flag is not zero
  print $0      # print the current line
}
$1 ~ /#BEGIN/ { # If we match the BEGIN line
  a=1           # Set a flag to one
}

為了避免在要打印的塊之前找到END行而退出,我們可以在退出前檢查標志是否已設置:

#!/usr/bin/awk -f
$1 ~ /#END/ && a != 0 {   # if we match the END line and the flag is set
  exit          # exit the process 
}
a != 0 {        # if the flag is not zero
  print $0      # print the current line
}
$1 ~ /#BEGIN/ { # If we match the BEGIN line
  a=1           # Set a flag to one
}

或簡明形式:

awk '$1~/#END/&&a{exit}a;$1~/#BEGIN/{a=1}' file

嘗試下面的sed命令以獲得所需的輸出-

vipin@kali:~$ sed  '/#BEGIN/,/#END/!d;/END/q' kk.txt|sed '1d;$d'
These lines should be extracted by our script.

Everything here will be copied.
vipin@kali:~$

說明-

使用d刪除兩個表達式之間的內容,但是!d會打印它們,然后q退出命令END地方q 1d;$d替換我們案例#BEGIN#END第一行和最后一行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM