2017-07-25 72 views
0

部分中的行的腳本我正在尋找想法讓腳本執行以下操作:用於計算不包括#

我有一個文本文件,例如: test.txt與它相似文本:

# 
# sectione 1 
# 
several 
text 
lines 
and so on 
# 
# sectione 2 
# 
more text 
and more 
# 
and more 
# ... 
# 
# sectione 3 
# 
more 
more 
more 
# 
# sectione 4 
# 
... 
... 

我需要一種可能性,只計算在sectione 2線和排除開頭的行#

在我上面的例子中的腳本應該顯示我「反3「在末尾 例如。

# counter_script.sh test.txt 
# 3 

這是可能性,我該怎麼辦? 我使用Debian Linux和bash shell。

回答

0

以下代碼只查找(第2節)的節數。嘗試下面,讓我知道這是否有幫助。

awk '/sectione 3/{a=""}/sectione 2/{a=1;next} !/#/ && a{count++} END{print count}' Input_file 

EDIT1:添加在同一個解決方案多現在也。

awk '/sectione 2/,/sectione 3/{count=$0!~/#/?++count:count} END{print count}' Input_file 
0

另一種方式:

sed -n '/# sectione 2/,/# sectione 3/{/^#/d;//!p;}' file | wc -l 

/# sectione 2/,/# sectione 3/選擇部分2和部分3

/^#/d刪除開始的行#

//!p打印其餘部分之間的界線..

0
sed -n '/sectione 2/,/sectione 3/{/^#/!p}' test.txt | wc -l 

在行的開始處處理第2部分和第3部分模式匹配的數據,然後打印任何不符合該模式的行!p。

1

您可以使用下面的命令awk

awk '/sectione/{f=$3==2?1:0}f&&!/^#/{c++}END{print c}' file 

說明在多行版本:

section2.awk:

/sectione/ { 
    # Set f(ound) to 1 (true) if the number between 'sectione' is a 2 
    # otherwise 0 (false) 
    f=$3==2?1:0 
} 

# If f(ound) is true (1) and the line starts not with a # 
# count it 
f&&!/^#/{ 
    c++ 
} 

# At the end of input print the c(ount) 
END{ 
    print c 
}