Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print lines from a file using sed, where the line numbers are stored as variables

I am trying to print out a specific section of a file which I have determined using line numbers, but the line numbers will vary from day to day so I need to be able to get the line numbers, store them as variables, then use sed to cut the lines from the stored file.

Here's what I have so far:

start-loader is a file that contains the lines I want to print, but also contains a lot of junk.

I can use sed -n '93,109p' start-loader to print out what I need, but what I want to do is this:

sed -n '$FL,$LFp' start-loader

where the variables are the line numbers I've stored.

I know that the above is not proper syntax, from a lot of research on the matter, but everything I've used either returns an error or does not work. I've tried double quotes, single then double for variables, braces for variables, and a few other things along with numerous different syntax styles. Would anyone happen to know how I can properly do this?

like image 753
bytesahoy Avatar asked Jan 14 '23 12:01

bytesahoy


2 Answers

You need to separate the p command from your last-line variable somehow. Either of the following should work:

$ sed -n "$FL,${LF}p" start-loader
$ sed -n "$FL,$LF p" start-loader

Without the separation, the shell would try to expand the variable LFp, which does not exist, resulting in an empty string being passed to sed and causing a syntax error.

You also need to use double-quotes, not single-quotes, to allow the variables to be expanded before sed sees them.

like image 181
chepner Avatar answered Jan 21 '23 10:01

chepner


I hope the example below answered your question:

kent$  s=3
kent$  e=8
kent$  seq 20 |sed -n "$s,$e p"
3
4
5
6
7
8
like image 37
Kent Avatar answered Jan 21 '23 09:01

Kent