用其他文本文件中的行替换文本文件中的行 [英] Replace line in text file with line from other text file
问题描述
我的问题是以下问题的变体:
My question is a variant of the following one:
问题在于用给定的字符串替换文件的第N行(替换行).就我而言,我不能只输入替换行,而是必须从另一个文件中读取它.
The problem there was to replace the Nth line of a file with a given string (a replacement line). In my case, I can't just type the replacement line, but I have to read it from another file.
例如:
textfile1:
textfile1:
my line
your line
his line
her line
textfile2:
textfile2:
our line
我想用textfile2中的行替换textfile1的第二行.
I want to replace the 2nd line of textfile1 with the line from textfile2.
我以为我可以阅读textfile2
I thought I could just read the textfile2
while IFS= read SingleLine
等然后使用 $ SingleLine
作为替换行,但是我失败了...根据我使用的引号类型(请原谅我的无知...),我最终将问题所在的行替换为文本 $ SingleLine 或使用 SingleLine 或仅收到错误消息:-[
etc. and then use $SingleLine
as the replacement line, but I failed... Depending on the type of quotes I used (please excuse my ignorance...) I ended up replacing the line in question with the text $SingleLine or with SingleLine or just getting an error message :-[
我确定您可以帮助我!
编辑解决方案:我花了点小钱就去寻找内联解决方案
EDIT about the solution: I went for the inline solution with the small change
sed '2d;1r textfile2' textfile1 > newfile1
要替换第N行,解决方法是(有关说明,请参阅有关接受的解决方案的评论)
To replace the Nth line, the solution would be (see comments on accepted solution for explanations)
sed 'Nd;Mr textfile2' textfile1 > newfile1
用N表示所需的行号,M = N-1.
with N the desired line number and M=N-1.
谢谢大家!
推荐答案
使用 sed
:
sed '2d;1r file2' file1
my line
our line
his line
her line
要进行内联
sed -i.bak '2d;1r file2' file1
这篇关于用其他文本文件中的行替换文本文件中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!