簡體   English   中英

Bash 打印兩個字符串之間的文件內容

[英]Bash print file contents between two strings

a
b
s
start
text
more text
end
even more text
end

我想打印startstart之后的第一個end之間的內容( start總是唯一的)。 我還想在打印文本的行之間打印,在本例中,在第 4 行和第 7 行之間。

我正在嘗試使用grepcat ,但我無能為力。

我試過了:

var=$(cat $path)
echo "$var" | grep -o -P '(?<=start).*(?=end)'

但它沒有打印任何東西,沒有grep ,它打印整個文件。

Output 在這個例子中應該是:

The content is between lines 4 and 7.

start
text
more text
end

With shell variables passed to awk and then print text by range then try, mention your shell variable inside start variable of awk and we should be Good then. (也將$0 ~ start更改為$0 ~ "^"start"$"以防您想在行中查找起始值的完全匹配。)

awk -v start="$your_shell_start_var" '
$0 ~ start,$0 ~ /^end$/{
  print
  if($0 ~ start){ startLine=FNR }
  if($0~/^end$/){ 
     print "The content is between lines " startLine " and " FNR
     exit
  }
}' Input_file

OP 樣品上的樣品 output:

start
text
more text
end
The content is between lines 4 and 7

簡單解釋:在此語句之間按范圍打印行,檢查條件是否行有end字符串然后start Input_file 出來,我們不需要讀取完整的 Input_file,因為 OP 只需要打印第一組行。

樣本數據:

$ cat -n strings.dat
 1  a
 2  b
 3  s
 4  start
 5  text
 6  more text
 7  end of more text
 8  end
 9  even more text
10  end

一個awk解決方案使用一個范圍(類似於 RavinderSingh13 的帖子),在最后打印出 OP 的文本消息:

startstring="start"                            # define start of search block

awk -v ss="${startstring}" '                   # pass start of search block in as awk variable "ss"

# search for a range of lines between "ss" and "end":

$0==ss,/^end$/ { if ($0==ss && x==0 ) x=FNR    # if this is the first line of the range make note of the line number
                 print                         # print the current line of the range
                 if ($0=="end")                # if this is the last line of the range then print our textual message re: start/finish line numbers
                    printf "\nThe content is between lines %d and %d.\n",x,FNR
               }
' strings.dat

注意$0==ss/^end$/測試假定數據文件中沒有前導/尾隨空格,否則這些測試將失敗並且沒有范圍匹配。

使用startstring="start"這會生成:

start
text
more text
end of more text
end

The content is between lines 4 and 8.

使用startstring="more text"這會生成:

more text
end of more text
end

The content is between lines 6 and 8.

使用startstring="even more text"這會生成:

even more text
end

The content is between lines 9 and 10.

使用startstring="water"這會生成:

--no output--

注意:如果 OP 使用startstring="end"結果與預期不符; 雖然可以添加更多代碼來解決這種情況,但我將暫時跳過這種情況。

暫無
暫無

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

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