When working with sed
it's almost always advisable to:
/address then/s/earch/replace/
There are two reasons for this. The first is that with multiple lines /addressing/
is faster - it's optimized only to find a match and doesn't bother selecting only portions of a line for editing and so it can narrow the results sooner.
The second reason is that you can play multiple edit operations off of the same address - it makes things much easier.
Of course, in this case, given only the data you show, it makes no practical difference. Still, this is how I would do the thing you ask about:
sed '/^[^%]*\|[^0-9]*$/s///g' <<\DATA
1: [18x14] [history 1/2000, 268 bytes] %3
2: [18x14] [history 1/2000, 268 bytes] %4 (active)
DATA
#OUTPUT
%3
%4
It just selects all characters that are non-% characters from the beginning of the line and all non-numeric characters from the end of the line in the address and then removes them with s///
- and that that's that.
In it's current form it might mangle data in unexpected ways if you feed it lines not containing a %digit
combo - and that's why addressing is important. If we alter it a little:
/%[0-9]/s/[^%]*\|[^0-9]*$//g
It gets safer and faster.
1: [18x14] [history 1/2000, 268 bytes] %3
and2: [18x14] [history 1/2000, 268 bytes] %4 (active)
I only want to get the%3
and%4
parts. The numbers can be up to999
.