Replace the first few lines with the first few lines from another 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 the first 4 lines from file1.dat with the first 3 lines from file2.dat. So my conclusion will follow

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

I tried the following input:

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

But with this input, I have the following output:

5
6
7
8
9
10

How do I change the input command? I tried various combinations.

+4
source share
3 answers

The following awkmay also help you with the same proven codes in GNU awk.

1st solution:

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

2nd solution:

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

3rd Solution: Using the command awkand headand tailhere.

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

Assuming GNU sed

$ sed '3q' f2 | sed -e '3r /dev/stdin' -e '1,4d' f1
1a
2a
3a
5
6
7
8
9
10
  • sed '3q' f2
  • -e '3r /dev/stdin' stdin
  • -e '1,4d'
  • - r, d


sed -e '3R f2' -e '3R f2' -e '3R f2' -e '1,4d' f1

r


GNU coreutils , , /

head -n3 f2; tail -n +5 f1
+2

awk -

Script

# awk 'NR==FNR && FNR<=3 || NR>FNR && FNR>4' file2 file1

1a
2a
3a
5
6
7
8
9
10

  • NR -
  • FNR - , .
  • true , awk .

:-)

+1

Source: https://habr.com/ru/post/1692533/


All Articles