DS-V
DS-V

Reputation: 123

How to use variables in bash sed command, specific example

I want to copy a section of a file to a new file. If I use:

sed -n '1641,1804p' oldfile.txt > newfile.txt

It works fine. BUT I want to replace the discreet numbers 1641 and 1804 with variables so I can use this code for different sized files. So I could have the variables instead:

$start=1641
$end=1804

I then want to pass these variables to sed. I use the following but it does not seem to work:

sed-n "$start,$endp" oldfile.txt > newfile.txt

Please help!

Upvotes: 2

Views: 135

Answers (3)

keithpjolley
keithpjolley

Reputation: 2263

You have "$" in front of the variables when you assign them which is incorrect.

To use shell variables that are concatenated with text or variables surround them with curly-braces so the shell knows where the variables end. In your example the shell is looking for the variable $endp which doesn't exist.

start=1641
end=1804
sed -n "${start},${end}p" oldfile.txt > newfile.txt

Upvotes: 2

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5591

Simply use like below:-

sed 's|'"$start"'|'"$end"'|g' oldfile.txt > newfile.txt

Upvotes: 1

vdavid
vdavid

Reputation: 2544

When you write sed -n "$start,$endp", the interpreter thinks you want to access the variable endp. You can fix this with braces, e.g.:

sed -n "${start},${end}p" oldfile.txt > newfile.txt

Upvotes: 1

Related Questions