SED: copy lines from a file to a specific line in another file

I can do this using the following example. The first command prints lines 16 ... 80 from file1to patch, and the second inserts the contents patchafter line 18 into file2:

sed -n 16,80p file1>patch
sed -i 18rpatch file2

However, I would like to copy directly from one file to another without using a temporary file between them, in one command using sed (not awk, etc.). I am sure that this is possible, I just don’t know how to do it.

+4
source share
3 answers

Doing this with sed requires some additional shell hype. Assuming bash, you can use

sed -i 18r<(sed '16,80!d' file1) file2

<(sed '16,80!d' file1) , sed '16,80!d' file1.

, , awk ( ), awk . :

awk 'NR == FNR { if(FNR >= 16 && FNR <= 80) { patch = patch $0 ORS }; next } FNR == 18 { $0 = patch $0 } 1' file1 file2

:

NR == FNR {                       # While processing the first file
  if(FNR >= 16 && FNR <= 80) {    # remember the patch lines
    patch = patch $0 ORS
  }
  next                            # and do nothing else
}
FNR == 18 {                       # after that, while processing the first file:
  $0 = patch $0                   # prepend the patch to line 18
}
1                                 # and print regardless of whether the current
                                  # line was patched.

. ;

cp file2 file2~
awk ... file1 file2~ > file2

, , .

+4

- , :

    head -80 file | tail -16 > patch

head .

+3
sed -i '1,15 d
        34 r patch
        81,$ d' YourFile

# oneliner version
sed -i -e '1,15 d' -e '34 r patch' -e '81,$ d' YourFile
  • .
  • ,

sed -i "1,16 d $(( 16 + 18 )) r patch 81,$ d" YourFile

.

  • r 1 , - , 80 - 16 .

, (, 34 18- ),

, :

  • 1,15 - , 16
  • 34 - 18- ( 16 ), 16 + 18 = 34
  • 81,$- trailing lines to delete, $means the last line, and 81 - the first line (after 80 taken) of unwanted ending lines.
0
source

All Articles