Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract lines between two line numbers in shell

Tags:

bash

shell

sed

How is this possible in shell using sed or any other filter

Lets say that i have two specific line numbers in two variables $line1 and $line2 and i want to extract lines between these two lines like this

cat my_file_path | command $line1 $line2

Example if my file is:

1:bbb

2:cccc

3:dddd

4:eeeee

My output should be if i do:

cat my_file_path | command 1 3

Output

bbb
cccc
like image 871
HobbitOfShire Avatar asked Feb 13 '14 16:02

HobbitOfShire


People also ask

How do you print a range of lines in Unix?

p - Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option. n - If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input.

Which command is used to extract specific lines records from a file?

The cut command offers many ways to extract portions of each line from a text file. It's similar to awk in some ways, but it has its own advantages and quirks. One surprisingly easy command for grabbing a portion of every line in a text file on a Linux system is cut.

How do you select a line in shell script?

Press Home key to get to the start of the line. For Selecting multiple lines, use Up/Down key.


1 Answers

Using sed:

$ cat my_file_path | sed -n "${line1},${line2}p"

or, even better (cat is somehow redundant):

$ sed -n "${line1},${line2}p" my_file_path
like image 67
Mihai Avatar answered Sep 21 '22 01:09

Mihai