![](/img/trans.png)
[英]Using grep and regex to get specific users list from etc/password
[英]grep filename with extension from a list of URLS using [regex]
大家好,我正在處理一個 url 列表,我只需要 grep 所有以 .asp 或 .aspx 結尾的文件名,也不應該有任何重復,所以我遇到了這個解決方案來刪除最后一個/
之前的所有內容.asp
之后
我嘗試了這個正則表達式,它刪除了最后一個/
之前的所有內容
([^\/]+$)
例如
abc/abc/abc/xyz.asp
>> xyz.asp
但是,如果在.asp
之后有/
,它會在/
之后開始選擇
abc/abc/abc/xyz.asp?ijk=lmn/opq
>> opq
我不想要
我只想 grep 具有.asp
和.aspx
的字符串,並刪除最后一個/
之前和之后的每個字符。
我簡單的話我要 grep filename.asp
名.asp 或filename.aspx
.aspx 而已
樣本輸入https://www.redacted.com/abc/xyz.aspx?something=something
樣品 output:
xyz.aspx
樣本輸入: https://www.redacted.com/abc/xyz/file.aspx?z=x&LOC=http%3A%2F%2Fwww.redacted.com%2Fasp%2Fanotherfile-asp%2F_%2FCRID--7%2Fthirdfile.asp%3Fui%3Dhash
樣品 output:
file.aspx, anotherfile-asp, thirdfile.asp
使用您顯示的示例,在 GNU awk
中,您可以嘗試使用正則表達式及其match
項以及與正則表達式一起使用的RS
function。
awk -v RS='[^.]*[-\\.]aspx?' '
RT{
num=split(RT,arr,"[/%2F]")
for(i=1;i<=num;i++){
if(arr[i]~/[-.]asp/){
print arr[i]
}
}
}
' Input_file
如果您的文件包含這兩行(顯示在您的問題中),那么示例 output 將如下所示:
xyz.aspx
file.aspx
anotherfile-asp
thirdfile.asp
解釋:簡單的解釋是,將整個 Input_file 的RS
(記錄分隔符)設置為[^.]*[-\\.]asp
。 然后在主程序中使用/%2F
吐出記錄並檢查是否有任何部分包含 -asp OR.asp 然后打印匹配的部分,如上面的示例 output 所示。
這是 Python,但正則表達式應該在其他地方工作。
import re
s1 = "https://www.redacted.com/abc/xyz.aspx?something=something"
s2 = "https://www.redacted.com/abc/xyz/file.aspx?z=x&LOC=http%3A%2F%2Fwww.redacted.com%2Fasp%2Fanotherfile-asp%2F_%2FCRID--7%2Fthirdfile.asp%3Fui%3Dhash"
# We want the set of things that is not a slash, until we get to .asp or
# .aspx, followed either by ? or end of string.
name = r"[^/]*\.aspx?((?=\?)|$)"
for s in s1,s2:
print( re.search( name, s ).group() )
Output:
xyz.aspx
file.aspx
另一種選擇可能是使用awk
並首先拆分不應成為結果一部分的部分。
然后從所有部分中,僅匹配不包含/
並以 asp 結尾並帶有可選 x 且前面為-
或 的字符串.
awk '
{
n = split($0 ,a, /(%[A-Z0-9]+)+/)
for (i=1; i <= n; i++) {
if (match(a[i], /[^/]+[.-]aspx?/)){
print substr(a[i], RSTART, RLENGTH)
}
}
}
' file
Output
file.aspx
anotherfile-asp
thirdfile.asp
xyz.aspx
如果支持 grep -P,您還可以使用:
grep -oP "(?:%[A-Z0-9]+)+(*SKIP)(*F)|(?:(?!%[A-Z0-9])[^/])*[-.]aspx?" file
查看正則表達式演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.