Is it possible to do simple arithmetic in sed addresses?
Judging by the “addresses” manual section, the answer seems no. But maybe there is a workaround?
For example, how can I print the second last line of a file? It would be cool something like:
sed -n '$-1 p' file
But it obviously does not work… so I usually have to do multiple sed calls, first for identifying the line, then do the arithmetic using the shell $((expr)) and then finally call sed again. Like this:
sed -n "$(($(sed -n '$ =' file)-1)) p" file
Is there a “better”, more compact, more readable way for doing arithmetics with sed addresses?
In a serious moment of procrastination, I decided to write a small script that quickly changes the xterm colorscheme. The idea is that you have the .Xresources a file with a start marker and an end marker:
...
START_MARKER
...
END_MARKER
...
and you want to delete everything that is between the markers, but not the markers themselves. Again, it would be great to do something like:
sed '/START_MARKER/+1,/END_MARKER/-1 d' file
…but you can’t!
You’re right, one can’t directly do math in sed1, even addresses. But you can use some trickery to do what you want:
Second-last row:
Between
STARTandEND:I’m using a BSD (mac)
sed; on GNU systems you can use;between lines instead of a newline. Or stick it in a script.1: Sed is Turing complete, so you can do math, but it’s unwieldy at best: http://rosettacode.org/wiki/A%2BB#sed
Yes, I know, UUOC; it’s for illustration only