[英]extract path between single quotes using grep
我正在使用 wget 下載文件,在此過程中,我會保存日志消息(見下文)以供以后使用。 最重要的部分是這一行Saving to: '/path/somefile.gz'
。
我想通了,如何使用grep Saving
提取此片段。
現在,我的問題是:如何僅提取單引號之間的路徑? '/path/somefile.gz' => /path/somefile.gz
HTTP request sent, awaiting response... 200 OK
Length: 15391 (15K) [application/octet-stream]
Saving to: ‘/path/somefile.gz’
0K .......... ..... 100% 79,7M=0s
2020-07-06 - ‘/path/somefile.gz’ saved [15391/15391]
Total wall clock time: 0,1s
Downloaded: 1 files, 15K in 0s (79,7 MB/s)
編輯
有沒有辦法以這種形式處理它?
wget -m --no-parent -nd https://someurl/somefile.gz -P ~/src/ 2>&1 |
grep Saving |
tee ~/src/log.txt
先感謝您!
來自wget
的示例 output :
$ cat wget.out
HTTP request sent, awaiting response... 200 OK
Length: 15391 (15K) [application/octet-stream]
Saving to: '/path/somefile.gz'
0K .......... ..... 100% 79,7M=0s
2020-07-06 - 'path/somefile.gz' saved [15391/15391]
Total wall clock time: 0,1s
Downloaded: 1 files, 15K in 0s (79,7 MB/s)
一種用於提取所需路徑/文件的awk
解決方案:
$ awk -F"'" ' # define input delimiter as single quote
/Saving to:/ { print $2 } # if line contains string "Saving to:" then print 2nd input field
' wget.out # our input
/path/somefile.gz # our output
要將以上內容保存到變量中:
$ wget_path=$(awk -F"'" '/Saving to:/ {print $2}' wget.out)
$ echo "${wget_path}"
/path/somefile.gz
跟進 OP 對問題的編輯...將wget
的 output 輸送到awk
解決方案中:
wget -m --no-parent -nd https://someurl/somefile.gz -P ~/src/ 2>&1 | awk -F"'" '/Saving to:/ {print $2}' | tee ~/src/log.txt
由於問題要求grep
中的解決方案,因此提取指定路徑的單個 GNU grep
命令可能是:
grep -Po "^Saving to: .\\K[^']*"
前提是 Perl 正則表達式在grep
中實現(並非所有grep
都實現了這些)。
當然,它也可以在 pipe 中使用:
wget_command | grep -Po "^Saving to: .\\K[^']*" | tee log.txt
請注意,我使用單引號 ( '
) 字符來錨定模式匹配表達式中的路徑末尾,但在問題中,Unicode 字符左單引號 (U+2018) ( '
) 和 Unicode 字符右單引號 ( U+2019) ( '
) 用於樣本輸入。 如果這確實是有意的,那么只需在上面的模式匹配表達式中將[^']
[^']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.