2

I have some variables:

$begin=10
$end=20

how to pass them to sed command.

sed -n '$begin,$endp' filename | grep word
sed -n '10,20p' filename | grep word
Maysam
  • 523
  • 4
  • 16
  • you can put the grepping logic in sed: try `sed -n "$begin,$end{/word/p}" file` – Kent May 28 '15 at 10:08
  • possible duplicate of [shell variables in sed script](http://stackoverflow.com/questions/7006910/shell-variables-in-sed-script) – NeronLeVelu May 28 '15 at 12:24

1 Answers1

3

The reason this doesn't work is that single quotes in shell code prevent variable expansion. The good way is to use awk:

awk -v begin="$begin" -v end="$end" 'NR == begin, NR == end' filename

It is possible with sed if you use double quotes (in which shell variables are expanded):

sed -n "$begin,$end p" filename

However, this is subject to code injection vulnerabilities because sed cannot distinguish between code and data this way (unlike the awk code above). If a user manages to set, say, end="20 e rm -Rf /;", unpleasant things can happen.

Wintermute
  • 42,983
  • 5
  • 77
  • 80