【发布时间】:2017-04-14 00:46:28
【问题描述】:
我有两个文件:
文件1:
key1
key2
key3
文件2:
some useful or useless text
::tok::
some more useful or useless text
我想创建多个文件:
file_key1:
some useful or useless text
key1
some more useful or useless text
file_key2:
some useful or useless text
key2
some more useful or useless text
file_key3:
some useful or useless text
key3
some more useful or useless text
在 sed 或 awk 方面,我是一个极端的菜鸟。我可以使用 perl 脚本或 bash 脚本执行上述操作。有没有办法使用 sed 或 awk 来做到这一点?
编辑:根据要求,我用来执行上述任务的 perl 脚本
$newFileCount= 1;
open IFH,$filename || die "cannot open the file";
sub CreateNewFiles{
my ($cid) = @_;
open TIFH, $templateFile; # this is the template file file2 from the above problem description
open OFH,">$templateFileTemp";
while(<TIFH>) {
s/::tok::/$cid/g;
print OFH $_;
}
close TIFH;
close OFH;
move($templateFileTemp,$newFilePrefix.$newFileCount.".ext"); # using a library File::Copy for move operation
}
while(<IFH>) {
chomp($_);
$newFileCount= $newFileCount + 1;
CreateNewFiles($_);
}
【问题讨论】:
-
如果可以在 perl 或 bash 脚本中完成,为什么要在 sed 或 awk 中完成?如果你这样做了......它可能会帮助你找到好的答案来展示你到目前为止所做的尝试。
-
@Sobrique 我只是想学习 sed/awk 做这些事情的方式。而且我一直面临着必须为最小的任务编写 perl 脚本的情况,我认为学习 sed/awk 绝对有价值,这将为我节省大量时间。无论如何,请参阅上面的编辑,我已经用 perl 脚本更新了问题
-
我只是不同意。
perl是一种编程语言,可以做任何事情。 -
并不是说 perl 不够用,我的缺点是不能在 perl 中快速编写脚本。我可能完全错误地假设 sed/awk 会为我加快速度,但这是我必须尝试得出的结论。感谢您的意见。