Giupo
Giupo

Reputation: 62

How to enter mathematical expressions inside the "sed" command?

given a list of numbers, I would like, through the "sed" command, to display only the lines in a range from 2 to a variable, to which 1 is subtracted. How can I subtract 1 to the variable inside the expression? I would not like solutions that create another variable before the command.

echo -e "1\n2\n3\n4\n5\n6\n7\n" | sed -n "3,+$var p"

this show 3-4-5-6 if $var=3. But if I wanted to print up to 5 (3-4-5), I would have to subtract 1 from the variable ($var-1).

I would like a way to insert ($var - 1)

Upvotes: 0

Views: 807

Answers (1)

anubhava
anubhava

Reputation: 785108

You can use $((...)) in shell for arithmetic avaulation:

echo -e "1\n2\n3\n4\n5\n6\n7\n" | sed -n "3,+$((var-1)) p"

3
4
5

I suggest using printf as it is more portable:

printf '%s\n' {1..7} | sed -n "3,+$((var-1)) p"

In bash you can use here-string and avoid pipeline:

sed -n "3,+$((var-1)) p" <<< $'1\n2\n3\n4\n5\n6\n7\n'

Upvotes: 3

Related Questions