Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
860 views
in Technique[技术] by (71.8m points)

linux - Replace first few lines with first few lines from other file

I am working on Linux. I have 2 files - file1.dat and file2.dat.

cat file1.dat
1
2
3
4
5
6
7
8
9
10

and for file2:

cat file2.dat
1a
2a
3a
4a
5a
6a
7a
8a
9a
10a

I want to replace first 4 lines from file1.dat with first 3 lines from file2.dat. So my output would be following

cat file1.dat
1a
2a
3a
5
6
7
8
9
10

I tried following input:

sed -i.bak '1,4d;3r file2.dat' file1.dat

But with this input I have following output:

5
6
7
8
9
10

How should I modify input command? I tried various combinations.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Following awk may also help you in same, tested codes in GNU awk.

Solution 1st:

awk 'FNR==NR && FNR<4{print;next} FNR>4 && FNR!=NR' file2.dat file1.dat

Solution 2nd:

awk 'FNR==NR && FNR==4{nextfile} FNR==NR{print;next} FNR>4 && FNR!=NR' file2.dat file1.dat
OR
awk 'FNR==NR{if(FNR==4){nextfile};print;next}  FNR>4 && FNR!=NR' file2.dat file1.dat

Solution 3rd: Using awk and head and tail command's combinations here.

awk 'FNR==1{system("head -n3 file2.dat");next} 1' <(tail -n +4 file1.dat)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...