Copy lines from x to y to another file

OS : RHEL 7.2
Shell : bash

I have a file which has lines like below

I want to copy from 2nd line to the 6th line and copy(redirect) those lines to another file.

$ cat patterns.txt 
hello world 
hello asia 
hello europe 
hello africa 
hello america 
hello antartica 
hello australia 
some more hellos 

So, the expected output will be like below.
Any way I could achieve this ?

$ cat patterns2.txt 
hello asia 
hello europe 
hello africa 
hello america 
hello antartica 
hello australia

Did you consider the head and tail *nix commands?

1 Like

Thanks for the tip Rudic

I am trying to print line 2 to 7th line using head command. But, I get the below errors. Can you guide me on the syntax.

$ head -n 2,7 patterns.txt
head: invalid number of lines: �2,7'
$ 
$ 
$ head -n 2 7 patterns.txt
head: cannot open '7' for reading: No such file or directory
==> patterns.txt <==
hello world
hello asia
$ 
$ head -n 2-7 patterns.txt
head: invalid number of lines: �2-7'

Try

head -7 file | tail +2
hello asia 
hello europe 
hello africa 
hello america 
hello antartica 
hello australia 
1 Like

Thanks Rudic

Your solution didn't work for me. Maybe bcoz the head and tail commands I use is GNU.

$ cat patterns.txt
hello world
hello asia
hello europe
hello africa
hello america
hello antartica
hello australia
some more hellos
$ 
$ head -7 patterns.txt
hello world
hello asia
hello europe
hello africa
hello america
hello antartica
hello australia
$ 
$ 
$ 
$ head -7 patterns.txt | tail +2
tail: cannot open '+2' for reading: No such file or directory
$ 
$ 
$ head -7 patterns.txt | tail 2
tail: cannot open '2' for reading: No such file or directory
$ 

BTW Is there sed/awk way to do this ?

It frequently helps to consult the man pages. man tail :

1 Like

You can also use awk:

awk "NR >= $from_line && NR <= $to_line {print}" $filename
1 Like

Hi Rudic,
I didn't quite get the post ( -n, --lines=[+]NUM ) on asking me to refer the manpage of tail command.

It principally reads: if tail +2 doesn't work for you (it does on my computer), try tail -n+2 . Generally: check the man page for your tool & version to find out what it provides and what it misses.

Shortest possible solution:

sed '2,6!d' file
1 Like

I would write tail -n +2 (with space). I think this is the "most canonical" form. On very old Unixes, the first variants of head and tail did not provide the -n switch. Then, for some time, I found it supported on several platforms, but marked as obsolete, and -n was favoured. Hence, even if the old form would still work, I would prefer using an explicit -n, simply for compatibility.

2 Likes