添加行到文件

时间:2014-02-18 09:28:59

标签: sed awk

我需要有关向文件添加一些行的帮助;对于expamle,我从文本grep这个参数grep并将其保存到File1:

cellIdentity="461"
cellIdentity="465"
cellIdentity="462"
cellIdentity="466"
cellIdentity="463"
cellIdentity="467"

现在我需要创建另一个文件,File2看起来像:

cellIdentity="461"
cellIdentity="465"
 cellIdentity="468"
cellIdentity="462"
cellIdentity="466"
 cellIdentity="469"
cellIdentity="463"
cellIdentity="467"
 cellIdentity="460"

我隔开了三条新线。 所以基本上,我需要添加这3行,最后一个数字8,9,0在这三行中始终是相同的,前两位数与其他行相同。 我不知道是否可以这样做。我正在尝试使用sed命令,但没有运气。 我在solaris中使用/ bin / csh。任何帮助/提示都会很棒。

由于

2 个答案:

答案 0 :(得分:4)

使用awk

awk 'BEGIN{split("8 9 0",a," ")}NR%2==0{t=$0;sub(/.$/,a[++i],$2);$0=t RS $0}1' FS=\" OFS=\" file

cellIdentity="461"
cellIdentity="465"
cellIdentity="468"
cellIdentity="462"
cellIdentity="466"
cellIdentity="469"
cellIdentity="463"
cellIdentity="467"
cellIdentity="460"

解释

  • FS=\" OFS=\"定义字段分隔符"
  • BEGIN{split("8 9 0",a," ")}在BEGIN部分
  • 中定义数组a中的8,9,0
  • NR%2==0找到奇数行
  • sub(/.$/,a[++i],$2)替换第2列中从数组a逐个获取的最后一个字符
  • 1与print
  • 相同

答案 1 :(得分:2)

这可能适合你(GNU sed):

sed -r '1{x;s/^/890/;x};2~2{p;G;s/(.)("\n)(.)(.*)/\3\2\4\3/;P;s/.*\n//;h;d}' file