从多个文件位置匹配后附加文本

时间:2016-04-22 01:14:06

标签: sed

对于编码来说,这是一个菜鸟所以请耐心等待......我正在尝试编写一个脚本,将3个独立文件中的数据输入到文本文件中的3个特定位置 - 例如: 编辑以便于阅读

#start of script
start_of_line1_text "$1" end_of_line1_text
start_of_line2_text "$2" end_of_line2_text
start_of_line3_text "$3" end_of_line3_text
#output to text when done   

$1 is the value in text1
$2 is the value in text2
$3 is the value in text3

我正在考虑使用sed但是无法弄清楚如何做到这一点......

或者只是在匹配random_text后在$ 1处插入一个单词?即:

sed '/start_of_line1_text/ a middle_of_line1_text' input

同样在更大的范围内 - 如果text1,2和3有多个值,你怎么能一次导入这些值1并每次保存一个新文件?例如:

text1 = 
a
b
c

text2 = 
e
f
g

text3 = 
h
i
j


#start of script
start_of_line1_text "line one of text1" end_of_line1_text
start_of_line2_text "line one of text2" end_of_line2_text
start_of_line3_text "line one of text3" end_of_line3_text
#output to text when done   

然后:

#start of script
start_of_line1_text "line two of text1" end_of_line1_text
start_of_line2_text "line two of text2" end_of_line2_text
start_of_line3_text "line two of text3" end_of_line3_text
#output to text when done   

我对使用的语言不挑剔我只是对如何适应这一切感到有些困惑....

非常感谢提前

2 个答案:

答案 0 :(得分:0)

此问题非常适合awk

尝试一下:

awk '!f[FNR] {f[FNR]=("out" FNR ".txt"); print "#start of script" >f[FNR]} {print "random_text \"" $0 "\" some_other_text" >f[FNR]} END {for(n in f) print "#output to text when done">f[n]}' text1 text2 text3

输出文件在当前目录out1.txtout2.txt等中生成。

您可以在命令末尾提供任意数量的文本文件作为输入。

脚本文件版本下面有附加参数:

#!/usr/bin/awk -f
!f[FNR] {
  f[FNR]=("out" FNR ".txt")
  print first >f[FNR]
}
{ 
  print start $0 end >f[FNR]
}
END {
  for(n in f) print last>f[n]
}

测试:

chmod +x ./script.awk
./script.awk -v first="#start of script"                          \
             -v start="random_text \"" -v end="\" some_other_text"\
             -v last="#output to text when done"                  \
             text1 text2 text3

答案 1 :(得分:0)

到目前为止我所拥有的是:

#!/usr/bin/perl

use strict;
use warnings;

sub rtrim { my $s = shift; $s =~ s/\s+$//;       return $s };

sub read_file_line {
my $fh = shift;

if ($fh and my $line = <$fh>) {
chomp $line;
return [split(/\t/,$line)];
}
return;
}

open(my $f1, "file1.txt");
open(my $f2, "file2.txt");
open(my $f3, "file3.txt");
open(FILE, ">group.txt") or die "Cannot open file";

my $pair1 = read_file_line($f1);
my $pair2 = read_file_line($f2);
my $pair3 = read_file_line($f3);

while ($pair1 and $pair2 and $pair3) {

printf '%s,',$pair1->[0] ;
printf "%s\n",$pair2->[0] ;
printf '%s,',$pair3->[0] ;

printf FILE " line1_text\n" ;
printf FILE " line2_text\n" ;
printf FILE " line3_text\n" ;
printf FILE " start_of_line4_text\"%s\end_of_line4_text\n",$pair3->[0] ;
printf FILE " start_of_line5_text\"%s\end_of_line5_text\n",$pair2->[0] ;
printf FILE " start_of_line6_text\"%s\end_of_line6_text\n",rtrim($pair1->[0]) ;
printf FILE " line7_text\n" ;
printf FILE " line8_text\n\n\n" ;



$pair1 = read_file_line($f1);
$pair2 = read_file_line($f2);
$pair3 = read_file_line($f3);

}

close($f1);
close($f2);
close($f3);
close(FILE) ;