Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

from=$1
to=$2

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

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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:

from=${1:-10}
to=${2:-20}

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading