如何在 bash 中将多个参数 URL 转换为单个参数 URL
How to convert multiple parameters URLs into single parameter URLs in bash
$ cat urls.txt
http://example.com/test/test/test?apple=&bat=&cat=&dog=
https://test.com/test/test/test?aa=&bb=&cc=
http://target.com/test/test?hmm=
我想要如下所示的输出,如何在 bash(单行命令)
中执行此操作
$ cat urls.txt
http://example.com/test/test/test?apple=
http://example.com/test/test/test?bat=
http://example.com/test/test/test?cat=
http://example.com/test/test/test?dog=
https://test.com/test/test/test?aa=
https://test.com/test/test/test?bb=
https://test.com/test/test/test?cc=
http://target.com/test/test?hmm=
使用 GNU awk
:
$ awk -F'?|=&|=' '{for(i=2;i<NF;i++) print "?" $i "="}' urls.txt
http://example.com/test/test/test?apple=
http://example.com/test/test/test?bat=
http://example.com/test/test/test?cat=
http://example.com/test/test/test?dog=
https://test.com/test/test/test?aa=
https://test.com/test/test/test?bb=
https://test.com/test/test/test?cc=
http://target.com/test/test?hmm=
我尝试使用 sed,但它很复杂。如果像这样使用 perl:
perl -pe 'if(/(.*\?)/){$url=;s#&#\n$url#g;}' url.txt
效果很好。
使用 GNU awk
使用 gensub()
:
awk '{print gensub(/^(https?:)(.*)(\?[[:alpha:]]+=)(.*)/,"\1\2\3","g")}' file
http://example.com/test/test/test?apple=
https://test.com/test/test/test?aa=
http://target.com/test/test?hmm=
gensub()
用于在替换文本中指定正则表达式的组件,使用正则表达式中的括号来标记组件(此处为四个)。我们只打印其中的 3 个:"\1\2\3"
.
这可能适合您 (GNU sed):
sed -E 's/(([^?]+\?)[^=]+=)&/\n/;P;D' file
用换行符和第一个参数之前的子字符串替换每个 &
,print/delete 第一行并重复。
$ cat urls.txt
http://example.com/test/test/test?apple=&bat=&cat=&dog=
https://test.com/test/test/test?aa=&bb=&cc=
http://target.com/test/test?hmm=
我想要如下所示的输出,如何在 bash(单行命令)
中执行此操作$ cat urls.txt
http://example.com/test/test/test?apple=
http://example.com/test/test/test?bat=
http://example.com/test/test/test?cat=
http://example.com/test/test/test?dog=
https://test.com/test/test/test?aa=
https://test.com/test/test/test?bb=
https://test.com/test/test/test?cc=
http://target.com/test/test?hmm=
使用 GNU awk
:
$ awk -F'?|=&|=' '{for(i=2;i<NF;i++) print "?" $i "="}' urls.txt
http://example.com/test/test/test?apple=
http://example.com/test/test/test?bat=
http://example.com/test/test/test?cat=
http://example.com/test/test/test?dog=
https://test.com/test/test/test?aa=
https://test.com/test/test/test?bb=
https://test.com/test/test/test?cc=
http://target.com/test/test?hmm=
我尝试使用 sed,但它很复杂。如果像这样使用 perl:
perl -pe 'if(/(.*\?)/){$url=;s#&#\n$url#g;}' url.txt
效果很好。
使用 GNU awk
使用 gensub()
:
awk '{print gensub(/^(https?:)(.*)(\?[[:alpha:]]+=)(.*)/,"\1\2\3","g")}' file
http://example.com/test/test/test?apple=
https://test.com/test/test/test?aa=
http://target.com/test/test?hmm=
gensub()
用于在替换文本中指定正则表达式的组件,使用正则表达式中的括号来标记组件(此处为四个)。我们只打印其中的 3 个:"\1\2\3"
.
这可能适合您 (GNU sed):
sed -E 's/(([^?]+\?)[^=]+=)&/\n/;P;D' file
用换行符和第一个参数之前的子字符串替换每个 &
,print/delete 第一行并重复。