简体   繁体   English

使用sed或awk用另一个文件的文本替换文本文件的行

[英]replacing lines of a text file with text of another file using sed or awk

I have a text file eg File1.txt and I want to replace its few lines with new lines available in another text file eg File2.txt. 我有一个文本文件,例如File1.txt,我想用另一个文本文件中的新行替换它的几行,例如File2.txt。 The format of File1.txt is as below It has pointers start and end. File1.txt的格式如下所示它有指针的开始和结束。

START

line 1
line 2
line 3 
line 4
line 5

END

I want to change line 1 to line 5 with the lines available in File2.txt. 我想用File2.txt中的可用行将第1行更改为第5行。 The number of lines are not equal in File1.txt and File2.txt. File1.txt和File2.txt中的行数不相等。 File2.txt may have more or less lines as in File1.txt. File2.txt可能有更多或更少的行,如File1.txt中所示。

I need input from someone. 我需要某人的意见。 Thanking in anticipation 感谢期待

If the parts of File1.txt that you want to preserve are fixed, you only need to print the second file and include that parts: 如果要保留的File1.txt部分是固定的,则只需打印第二个文件并包含以下部分:

printf 'BEGIN\n\n%s\n\nEND\n' "$(<File2.txt)"

IF that's not the case (substitute START/END with the patterns that match the parts that you want to preserve): 如果不是这种情况(将START / END替换为与您要保留的部分匹配的模式):

awk 'NR == FNR {
  f2 = f2 ? f2 RS $0 : $0
  next
  }
/START|END/ || !NF {
  print; next  
  }
NF && !c++ { 
  print f2 
  }' File2.txt File1.txt

This GNU sed one liner might work: 这个GNU sed one liner可能有效:

sed -re '/^START/,/^END/{/^START/{p;r File2.txt' -e '};/^END/p;d}' File1.txt

This inserts File2.txt between START and END but doesn't preserve empty lines after line 1 and before line 2 File2.txtSTARTEND之间插入File2.txt ,但不会在line 1行之后和line 2 line 1之前保留空行

This tries to preserve empty lines: 这会尝试保留空行:

sed -re '/^START/,/^END/{//!{/^$/{p;d};x;/./{x;d};x;h;r File2.txt' -e ';d};x;s/.*//;x}' File1.txt

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

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