我正在尝试使用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.zip
和foo_bar-12345.zip
而不是foo_bar-12345_dup.zip
。
我需要一些方向来实现这一目标。
答案 0 :(得分:0)
您可以尝试像(foo_bar\.zip)|(foo_bar-\d+\.zip)
这样的正则表达式。这意味着您接受的字符串是&#34; foo_bar.zip&#34;或者这样的字符串&#34; foo_bar&#34;之后是一个短划线和至少一个数字(以及最终的&#34; .zip&#34;)。当然,你应该替换&#34; foo_bar&#34;乘以${file_name}
。
答案 1 :(得分:0)
您可以使用grep
和正则表达式提取文件名部分并将其传递给awk
以获取文件名部分(假设您的文件具有.zip扩展名):
curl ... | grep -oE '>[[:alpha:]_]+\.zip<|>[[:alpha:]_]+-[[:digit:]]+\.zip<' | awk -F '[<>]' '{print $2}'
对于您的样本,您将获得:
foo_bar.zip
foo_bar-12345.zip
答案 2 :(得分:0)
curl command | grep -oP ">\K\w+-?\d*.zip"
>\K
:积极的lookbehind:匹配前面的字符串>
但忽略>
作为匹配的一部分;
\w+-?\d*.zip
:你需要的正则表达式;
输出:
foo_bar.zip
foo_bar-12345.zip
答案 3 :(得分:0)
卷曲的东西| awk -F&#39; [&#34;&gt;]&#39; &#39;!/ _ dup /&amp;&amp; / _ bar / {print $ 2}&#39;
foo_bar.zip
foo_bar-12345.zip
答案 4 :(得分:0)
请您试着跟随并告诉我这是否对您有帮助。
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.