简体   繁体   English

如何通过将Grep输出管道传输到sed来添加变量模式?

[英]How To Prepend Variable Pattern By Piping Grep Output To Sed?

I have the following data in two files: 我在两个文件中包含以下数据:

domains.txt contains: domains.txt包含:

http://example1.com

urls.txt contains: urls.txt包含:

http://example1.com/url-example/
http://example5.com/url-example/
http://example2.com/url-example/

Using the following command (I'm using this structure because usually there is more in the files and this is just a minimal example): 使用以下命令(我使用此结构,因为通常文件中包含更多内容,这只是一个最小的示例):

cat domains.txt | while read LINE; do grep -m 1 "$LINE" urls.txt

This will give me the matching line. 这将给我匹配的行。

http://example1.com/url-example/

However, I would like the desired output to be: 但是,我希望期望的输出是:

http://example1.com,http://example1.com/url-example/

I would like to add a pipe that would prepend the "LINE" variable before the matched output. 我想添加一个管道,该管道将在匹配的输出之前添加"LINE"变量。 I was thinking something with sed should be easy? 我在想用sed做事应该容易吗? Your input is highly appreciated. 非常感谢您的投入。

Update: 更新:

Although this is easy with awk , if someone has an answer with piping the output, I would like to use that to go with the script. 尽管使用awk很容易,但是如果有人对管道输出有答案,我想将其与脚本一起使用。

while IFS= read -r line; do echo -n "$line,"; grep -m 1 "$line" urls.txt; done < domains.txt

This is very easy to do using awk: 使用awk可以很容易地做到这一点:

while read LINE; do awk -v pattern="$LINE" '$0 ~ pattern { print pattern "," $0 }' urls.txt; done < domains.txt

Or using sed: 或使用sed:

while read LINE; do sed -ne "s?$LINE.*?$LINE,&?p" urls.txt; done < domains.txt

To answer your follow-up question, to limit the result to the first match using awk: 要回答您的后续问题,请使用awk将结果限制为第一个匹配项:

while read LINE; do awk -v pattern="$LINE" '$0 ~ pattern { print pattern "," $0; exit }' urls.txt; done < domains.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM