Replace first few lines with first few lines from other file

后端 未结 3 387
夕颜
夕颜 2020-12-18 10:10

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 file         


        
相关标签:
3条回答
  • 2020-12-18 10:15

    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)
    
    0 讨论(0)
  • 2020-12-18 10:30

    awk is your friend

    Script

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

    Output

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

    Tips

    • NR - Total number of records processed
    • FNR - Total number of records processed but resets when reading a new file.
    • When a condition evaluates to true and no extra commands are given,awk just prints.

    All good :-)

    0 讨论(0)
  • 2020-12-18 10:34

    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 gives the first three lines from second file
    • -e '3r /dev/stdin' use stdin data
    • -e '1,4d' delete required lines
    • order is important - first r then d


    For small number of lines, you can also use

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

    R command reads one line at a time


    With GNU coreutils, this would probably be better for all/most scenarios

    head -n3 f2; tail -n +5 f1
    
    0 讨论(0)
提交回复
热议问题