[英]Reading a subset of the lines in a text file, with bash
我有一個文件
line a - this is line a
line b - this is line b
line c - this is line c
line d - this is line d
line e - this is line e
問題是:如何使用bash命令輸出從“line b”開始直到“line d”的行? 我的意思是,獲得:
"line b - this is line b
line c - this is line c
line d - this is line d"
sed -n '/line b/,/line d/p' file
您的示例不足以在一般情況下推斷出您想要的內容,但假設您要刪除第一行和最后一行,則可以使用
tail -n+2 $filename | head -n-1
這里tail -n+2
打印從第二行開始的所有行, head -n-1
打印除了last之外的所有行。
對於您的樣本數據集:
awk '/line b/,/line d/' file
要么
awk '/line d/{f=0;print}/line b/{f=1}f' file
如果用bash,你的意思實際上是單獨打擊,我無法幫助你。 你真的應該使用正確的工具來完成工作。 如果你的意思是你可以從bash調用的標准UNIX實用程序,我將使用awk
。
echo 'line a - this is line a
line b - this is line b
line c - this is line c
line d - this is line d
line e - this is line e' | awk '
BEGIN {e=0}
/^line b/ {e=1}
/^line d/ {if (e==1) {print;exit}}
{if (e==1) print}
'
這輸出:
line b - this is line b
line c - this is line c
line d - this is line d
它的工作方式很簡單。
我在這里做了一個假設,除非你已經回應,否則你不想退出d行。 如果這是錯誤的,請將出口移到行d的if語句之外:
/^line d/ {if (e==1) print;exit}
然后,如果你在你的第b行之前得到一行,它就會退出而不會回響任何東西。
"/^line X/"
-type子句可以非常強大,可以很好地匹配你可以拋出的任何東西。
你可以單獨使用bash來做,雖然我同意Pax使用其他工具可能是一個更好的解決方案。 這是一個僅限bash的解決方案:
while read line
do
t=${line#line b}
if test "$t" != "$line"
then
echo $line
while read line
do
echo $line
t=${line#line d}
if test "$t" != "$line"
then
exit 0
fi
done
fi
done
另一種方法取決於你的意思:
pcregrep -m 'line b - this is line b
line c - this is line c
line d - this is line d' file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.