【问题标题】:For each line, create a new line to append with mutliple entries from another file对于每一行,创建一个新行以附加来自另一个文件的多个条目
【发布时间】:2017-10-04 18:36:56
【问题描述】:

好吧,我又为你们中的一位出色的巫师带来了另一个没有脑子的东西,我一直在玩 awk,但还没有完全弄清楚这一点。因此,事不宜迟,这就是我要解决的问题。

我有两个文件

file1 看起来像这样(实际文件有数百行 w 随机单词)

somewebsite
someotherwebsite
somestinking
blahblah
foobar

file2 看起来像这样(许多 tld,更多)

.com.th
.co.uk
.com
.de
.ath.cx

好的,我需要 file1 中的每一行将每个 tld 从 file2 添加到一个新行上......

更详细地说,需要复制 file1 中的每一行,以便可以将 file2 中的每个 tld 添加到 file1 中的每个条目。

输出应该是这样的:

   somewebsite.com.th
   somewebsite.co.uk
   somewebsite.com
   somewebsite.de
   somewebsite.ath.cx
   someotherwebsite.com.th
   someotherwebsite.co.uk
   someotherwebsite.com
   someotherwebsite.de
   someotherwebsite.ath.cx
   somestinking.com.th
   somestinking.co.uk
   somestinking.com
   somestinking.de
   somestinking.ath.cx
   blahblah.com.th
   blahblah.co.uk
   blahblah.com
   blahblah.de
   blahblah.ath.cx
   foobar.com.th
   foobar.co.uk
   foobar.com
   foobar.de
   foobar.ath.cx

我希望这对某人有意义,我试图弄清楚如何去做,这当然很有趣我失败的​​所有方式。

提前谢谢你。我确信我不是唯一一个现在、过去或将来尝试过这个的人,所以一个解决方案肯定会帮助下一个尝试这样做的人。

【问题讨论】:

  • 您应该:1.) 添加您的代码,或者 2.) 只是说:我很懒,所以为我编写一个脚本
  • 我真的在寻求帮助。那些类型的评论是不必要的。
  • 您应该阅读help center。在这里,我们帮助开发人员克服工作中的问题。您没有发布任何可以称为“工作”的内容,因此您甚至没有尝试解决问题。因此,您只是要求免费的开发人员工作,却错过了网站的重点。

标签: bash awk sed


【解决方案1】:

在 awk 中:

$ awk 'NR==FNR{a[$1];next}{for(i in a) print $1 i}' file2 file1
somewebsite.co.uk
somewebsite.de
somewebsite.com
somewebsite.ath.cx
somewebsite.com.th
...

由于in 运算符的性质,tld 的出现顺序是随机的。

或者只使用join(和tr):

$ join  -j 2 file1 file2 | tr -d ' '
somewebsite.com.th
somewebsite.co.uk
somewebsite.com
somewebsite.de
...

【讨论】:

  • +++ 用于join。无论如何 - 你可以只 join -j 2 -t '' file1 file2 例如指定 -t - 分隔符为空字符串。
  • @jm666 我确实尝试过,但我得到了成对的项目,并且这些项目由空行分隔。它对你有用吗? (加入(GNU coreutils)8.21)
  • Arghhh ;( - 那么join 的 BSD 版本与 GNU 版本不同。我使用 OS X 所以在 BSD 中它可以工作,但你是对的 - 在 GNU join 中没有.
  • @jm666 适用于join (GNU coreutils) 8.22
  • 我认为通过尝试加入一个不存在的领域,你处于最深、最黑暗的未定义行为领域,所以 YMMV。至少我在the POSIX spec 或任何join 手册页中找不到任何说明应该做什么的内容。 +1 用于 awk。
【解决方案2】:

试试这个 -

$head file?
==> file1 <==
somewebsite
someotherwebsite
somestinking
blahblah
foobar

==> file2 <==
.com.th
.co.uk
.com
.de
.ath.cx
$while read a; do while read b; do echo "$a$b"; done < file2; done < file1
somewebsite.com.th
somewebsite.co.uk
somewebsite.com
somewebsite.de
somewebsite.ath.cx
someotherwebsite.com.th
someotherwebsite.co.uk
.....
.....

【讨论】:

  • 这正是我所希望的,感谢您以实用而优雅的答案回答了我的问题,非常感谢您。
  • @derpderpalert - 欢迎 :)
  • 请务必阅读 why-is-using-a-shell-loop-to-process-text-considered-bad-practice 以了解不这样做的一些原因(例如,它的效率极低,并且在某些输入的情况下会产生意外/不正确的输出)。
  • 天哪,我想知道如果我的某些条目看起来像 some-website-with-dashed.com 或 some_other_website.sucks 会发生什么
  • @derpderpalert - 如果您遇到任何问题/错误输出,请尝试使用上述命令并分享结果。
猜你喜欢
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
  • 2016-06-25
  • 2014-09-30
相关资源
最近更新 更多