[英]How do I replace all lines after line XX in one file with content from another file?
I'm on Debian 8.2. 我使用的是Debian 8.2。 Here's
test.sh
so far. 到目前为止,这里是
test.sh
#!/bin/bash
wget http://winhelp2002.mvps.org/hosts.txt -O fileA
tail -n +26 fileA >> fileB
I want lines 26 onwards of fileA
's content to replace everything in fileB
from line 26 onward — so I end up with the first 25 lines of the output are from lines 1-25 of the original fileB
and the remainder is lines 26 onwards of fileA
. 我想从文件
fileA
的内容开始的第26行替换fileB
从第26行开始的所有内容-所以我最后输出的前25行是从原始fileB
第1-25行开始,其余的是从行26开始fileA
。
How do I do this? 我该怎么做呢?
If you want the whole of fileA
, you could use: 如果您想要整个
fileA
,则可以使用:
sed -i.bak -e '26r fileA' -e '26,$d' fileB
This reads the contents of fileA
into the output after reading line 26 (but before printing or otherwise processing it); 这将在读取第26行之后(但在打印或进行其他处理之前)将
fileA
的内容读取到输出中; it then deletes lines 26 to the end of fileB
. 然后删除第26行到
fileB
。 The -i.bak
option means that fileB
is overwritten with the output of the command (but a backup copy is made with suffix .bak
). -i.bak
选项意味着该命令的输出将覆盖fileB
(但后缀.bak
会创建一个备份副本)。 Different versions of sed
handle 'no backup' with -i
differently; 不同版本的
sed
使用-i
处理“不备份”的方式有所不同; this will work with both (all?) of them. 这将与他们两个(全部?)一起使用。 If you use GNU
sed
, -i
on its own is sufficient; 如果您使用GNU
sed
,那么-i
本身就足够了; if you use Mac OS X (BSD) sed
, you need -i ''
to specify it. 如果使用Mac OS X(BSD)
sed
,则需要-i ''
进行指定。
The question has been clarified so it requires lines 1-25 of the original fileB
and lines 26-EOF of the original fileA
in the output file fileB
. 这个问题已得到澄清,因此需要线原来的1-25
fileB
和线原来的26 EOF fileA
输出文件fileB
。 This is a tad fiddly, not least because process substitution only works outside quotes. 这有点奇怪,尤其是因为进程替换仅在引号之外起作用。 On systems where
/dev/stdin
is available (most Unix-like systems), you could use: 在
/dev/stdin
可用的系统上(大多数类似Unix的系统),可以使用:
sed 1,25d fileA | sed -i.bak -e '26r /dev/stdin' -e '26,$d' fileB
The first sed
command deletes lines 1-25 of fileA
and writes the result (lines 26-EOF) to its standard output, which is the standard input of the second sed
command. 第一个
sed
命令删除fileA
的第1-25行, fileA
结果(第26-EOF行)写入其标准输出,该输出是第二个sed
命令的标准输入。 The second sed
command reads the file from /dev/stdin
when it reaches line 26 of fileB
, and then deletes lines 26-EOF of fileB
, with overwriting as before. 第二条
sed
命令在到达文件B的第26 fileB
从/dev/stdin
读取文件,然后删除文件B的第26-EOF fileB
,并像以前一样进行覆盖。
NB: A previous version of this answer used 25r
instead of 26r
; 注意:此答案的先前版本使用
25r
而不是26r
; this was an off-by-one error that's now fixed. 这是一个一次性的错误,现已修复。
#!/bin/bash
wget http://winhelp2002.mvps.org/hosts.txt -O fileA
head -25 fileB > tempfile && mv tempfile fileB
tail -n +26 fileA >> fileB
head -25
will take first 25 lines from fileB and dump it to tempfile. head -25
将从fileB提取前25行,并将其转储到tempfile。 Then tempfile will be renamed to fileB. 然后将tempfile重命名为fileB。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.