Username
Username

Reputation: 3663

How do I replace all lines after line XX in one file with content from another file?

I'm on Debian 8.2. Here's test.sh so far.

#!/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.

How do I do this?

Upvotes: 0

Views: 48

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754130

If you want the whole of fileA, you could use:

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); it then deletes lines 26 to the end of 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). Different versions of sed handle 'no backup' with -i differently; this will work with both (all?) of them. If you use GNU sed, -i on its own is sufficient; if you use Mac OS X (BSD) sed, you need -i '' to specify it.


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. 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:

 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. 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.

NB: A previous version of this answer used 25r instead of 26r; this was an off-by-one error that's now fixed.

Upvotes: 4

zedfoxus
zedfoxus

Reputation: 37079

#!/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. Then tempfile will be renamed to fileB.

Upvotes: 2

Related Questions