Ubuntu – Cut specific lines of a file and paste them at the end of another file

command linetext processing

Suppose I want to cut more than one interval of lines from one file (eg., lines 1-500, 1029-1729 and 2696-3446), appending values at the end of another file (output.txt) and eliminating these values from the first file. The origin is a file with 9277 lines, I want to cut some of them, eliminating them from the original file and pasting them into another file. Is that possible via command line?

Best Answer

Using sed, you can write a set of lines to a different file while deleting it from the current file like so:

sed -i -e 'N, M { w output.txt
d }' input.txt

where N and M are the line numbers. The -i option makes sed save changes to the source file, and here the d command deletes to those lines. At the same time, w output.txt causes the selected lines to be written to output.txt. And yes, those are two separate lines: sed requires that the w command's filename be till a newline.

So you can do something like:

cmd=' { w output.txt
d }'
sed -i -e "1,500 $cmd" -e "1029,1729 $cmd" -e "2696,3446 $cmd" input.txt