簡體   English   中英

通過正則表達式從curl輸出中提取子字符串

[英]Extracting a substring from curl output through a regex

我正在嘗試一個shell腳本附帶的腳本,該腳本需要獲取特定格式的zip文件,例如"${file_name}-12345.zip""${file_name}.zip"

此shell腳本的輸入將是curl命令的輸出,如下所示,子字符串為"${file_name}" 在這種情況下, file_name=foo_bar

<img src="/icons/compressed.gif" alt="[   ]"> 
<a href="foo_bar.zip">foo_bar.zip</a>
<img src="/icons/compressed.gif" alt="[   ]"> 
<a href="foo_bar-12345.zip">foo_bar-12345.zip</a>
<img src="/icons/compressed.gif" alt="[   ]"> 
<a href="foo_bar-12345_dup.zip">foo_bar-12345_dup.zip</a>

我只需foo_bar.zipfoo_bar-12345.zip ,而不foo_bar-12345_dup.zip

我需要一些指導來實現這一目標。

您可以嘗試(foo_bar\\.zip)|(foo_bar-\\d+\\.zip)這樣的正則表達式。 這意味着您接受的字符串為“ foo_bar.zip”或諸如“ foo_bar”后接短划線和至少一位數字(以及最后的“ .zip”)的字符串。 當然,您應該用${file_name}的值替換“ foo_bar”。

您可以使用grep和一個正則表達式提取文件名部分,並將其通過管道傳輸到awk以獲得文件名部分(假設文件的擴展名為.zip):

curl ... | grep -oE '>[[:alpha:]_]+\.zip<|>[[:alpha:]_]+-[[:digit:]]+\.zip<' | awk -F '[<>]' '{print $2}'

對於您的示例,您將獲得:

foo_bar.zip
foo_bar-12345.zip
curl command | grep -oP ">\K\w+-?\d*.zip" 

>\\K :正回顧后:提前匹配字符串>但是忽略>作為匹配的一部分;
\\w+-?\\d*.zip :您所需的正則表達式;

輸出:

foo_bar.zip
foo_bar-12345.zip

卷曲東西| awk -F'[“>]''!/ _ dup / && / _ bar / {print $ 2}'

foo_bar.zip
foo_bar-12345.zip

您能否嘗試遵循並讓我知道這是否對您有幫助。

awk 'sub(/.[^>]*/,"") && gsub(/>|<.*/,"") && (($0 ~ /foo_bar.zip/) || ($0 ~ /foo_bar-[0-9]+.zip/))'  Input_file

溶液的非單一襯里形式也如下。

awk '
sub(/.[^>]*/,"") && \
gsub(/>|<.*/,"") && \
(($0 ~ /foo_bar.zip/) || ($0 ~ /foo_bar-[0-9]+.zip/))
'   Input_file

輸出如下。

foo_bar.zip
foo_bar-12345.zip

說明:也添加了一個非襯套形式的解決方案並帶有說明:

awk '
sub(/.[^>]*/,"") && \
gsub(/>|<.*/,"") && \
(($0 ~ /foo_bar.zip/) || ($0 ~ /foo_bar-[0-9]+.zip/))
##Substituting everything from starting to till first occurrence of > comes with NULL by using awk out of the box utility called sub.
##Globally substituting either > with NULL OR starting from < to everything with NULL.
##Now checking if after substituting above mentioned substitutions a line is equal to either foo_bar.zip OR foo_bar- then all digits till .zip
## Now point to be noted here that all conditions are joined with && means if first sub then gsub and then either of 3rd condition matches then only it should print line. awk works on condition then action method, in this solution I had mentioned conditions and NO action, so by default print of current line will happen.
' Input_file ## mentioning Input_file name here.

暫無
暫無

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

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