An ancient version of ipconfig
(inside initramfs) requires its user input to supply only up to 7 colon separated elements, like:
ip=client-ip:server-ip:gw-ip:netmask:hostname:device:autoconf
result in an ipconfig
error when users do supply more than 7 elements.
Therefore the extra (2 DNS resolvers) should be chopped off.
That can be done inside a subshell
with cut
, like:
validated_input=$(echo ${user_input} | cut -f1,2,3,4,5,6,7 -d:)
How can such cut
be written using (b)ash
parameter expansion/substitution?
Without:
- launching subshell(s)/subprocess(es) (piping)
- IFS-wrangling/mangling
Because of (1) speed, see Using bash variable substitution instead of cut/awk, and (2) learning.
In other words: How to do a lookup for n-th (7-th) character occurrence and remove/trim everything from there until the end of the string?
Best Answer
This uses only parameter expansion:
Example:
Thanks ilkkachu for coming up with a fix to the trailing
:
!This will attempt to match the beginning of your parameter, and if it does it will strip it.
Example:
This will attempt to match the end of your parameter, and if it does it will strip it.
Example:
So in the answer:
(note the quotes around
${var#...}
so that it is treated as a literal string (not a pattern) to be stripped off the end of$var
).When applied to:
${var#*:*:*:*:*:*:*:}
=morefields:another:youwantanother:haveanother:
That is expanded inside
${var%: ... }
like so:${var%:morefields:another:youwantanother:haveanother:}
So you are saying give me:
But trim
:morefields:another:youwantanother:haveanother:
off the end.The Bash Reference Manual (3.5.3)