How to filter lines with sed and variables?


I am trying to create sed script, where the user supplies which lines would be filtered, however I can’t figure out how to apply the variables.


if [[ -z $1 ]]
    then from=10

if [[ -t $2 ]]
    then to=20

result=$(sed -n -e '10,20p' /usr/share/wordlists/rockyou.txt)

printf "%s\n" $result

I tried supplying variables directly into the sed script, but that only threw me some errors.

>Solution :

You can use the variables in the sed script by referencing them in the expression. Here’s an updated version of your script that uses the variables:


result=$(sed -n "${from},${to}p" /usr/share/wordlists/rockyou.txt)

printf "%s\n" "$result"

The from variable is set to the value of the first argument, or to 10 if the first argument is not supplied. The to variable is set to the value of the second argument, or to 20 if the second argument is not supplied.

These variables are then used in the sed expression by wrapping them in double quotes and referencing them directly.

Leave a ReplyCancel reply