Re: extract array name from string
On Wednesday 30 April 2008 04:40, Eric wrote:
> I've got a text file with names like this:
> Variable1[30]
> extraVar22[22]
> Test42Exists[104]
>
> how do i get just the array name in each case
> e.g.:
> N="Variable1[30]"
> echo "$N"|sed <what goes here>"
> or
> echo "$N"|eval match "$N" \(<what goes here>\)"
>
> the output would be Variable1 (dropping the [30])
>
> It can be sed or bash, or whatever, I'm using this in a bash script.
> I was playing with echo 'eval match "$N" \( stuff here \)'
> but i couldnt get it to work right, array names can be a mix of upper and
> lower case, numbers (and possibly underscores).
Plenty of ways to do that, in addition to cut, which was already suggested.
$ printf "%s\n" 'Test42Exists[104]' | awk -F'[' '{print $1}'
Test42Exists
$ printf "%s\n" 'Test42Exists[104]' | sed 's/\[[^]]*\]$//'
Test42Exists
$ expr 'Test42Exists[104]' : '\([^[]*\)'
Test42Exists
$ expr match 'Test42Exists[104]' '\([^[]*\)'
Test42Exists
$ var='Test42Exists[104]'
$ printf "%s\n" "${var%\[*\]}"
Test42Exists
And, since you use bash:
$ var='Test42Exists[104]'
$ printf "%s\n" "${var/%\[*\]/}"
Test42Exists
--
D.
|