46

I want to copy lines 10 to 15 of a file into another file in Unix.

I am having files file1.txt and file2.txt.

I want to copy lines 10 to 15 from file1.txt to file2.txt.

iBug
  • 35,554
  • 7
  • 89
  • 134
sri
  • 527
  • 2
  • 6
  • 11
  • 2
    Possible duplicate of [How can I extract a predetermined range of lines from a text file on Unix?](https://stackoverflow.com/questions/83329/how-can-i-extract-a-predetermined-range-of-lines-from-a-text-file-on-unix) – etopylight Nov 15 '17 at 03:09

2 Answers2

68

Open a terminal with a shell then

sed -n '10,15p' file1.txt > file2.txt

Simple & easy.

If you want to append to the end instead of wiping file2.txt, use >> for redirection.

sed -n '10,15p' file1.txt >> file2.txt
                          ^^

AWK is also a powerful command line text manipulator:

awk 'NR>=10 && NR<=15' file1.txt > file2.txt
iBug
  • 35,554
  • 7
  • 89
  • 134
  • 1
    what if the `file2.txt ` has some contents and we want to insert at the start of `file2.txt` @iBug – JigarGandhi Jul 09 '20 at 05:16
  • @JigarGandhi "Insert at start" is really another topic. Your best bet is to save the output to `file3.txt` and then append the original file (`cat file2.txt >> file3.txt`). – iBug May 17 '21 at 09:54
  • If I want to pass the line number 10 & 15 of sed using two variables say start_line & end_line then what to do? – Soumyadip Das Jun 02 '22 at 13:41
  • 1
    @SoumyadipDas Just use shell variable processing: `sed -n "${start_line},${end_line}p"`. Make sure you avoid single quotes where no variable substitution happens. – iBug Jun 02 '22 at 13:49
  • Nice, it's the easiest one. I did something with the help of https://askubuntu.com/a/76842 and working, but I will now use your's solution in my shell. – Soumyadip Das Jun 02 '22 at 13:57
15

In complement to the previous answer, you can use one of the following 3 solutions.

sed

Print only the lines in the range and redirect it to the output file

sed -n '10,15p' file1.txt > file2.txt

head/tail combination

Use head and tail to cut the file and to get only the range you need before redirecting the output to a file

head -n 15 file1.txt | tail -n 6 > file2.txt

awk

Print only the lines in the range and redirect it to the output file

awk 'NR>=10 && NR<=15' file1.txt > file2.txt
Allan
  • 12,117
  • 3
  • 27
  • 51
  • 2
    The head/tail is only an accomplishment of the job, not a good answer in fact. The AWK solution is a really good one. – iBug Nov 15 '17 at 05:46