LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   bash: removing whitespace filled element from array (https://www.linuxquestions.org/questions/linux-newbie-8/bash-removing-whitespace-filled-element-from-array-4175478759/)

ezekieldas 09-27-2013 11:15 AM

bash: removing whitespace filled element from array
 
First off, I have to do this in bash. I realize there are other langs better suited but doing it in shell is a hard requirement.

I have a section of this script where I get a blob of data and start working with it as an array. There's this one section that is problematic, I want to get rid of the entire key/value "comments." I can get rid of the key, "comments=" (see below) but I need something that keeps going until it gets to "enabled." Any ideas as to how I might do this? I found a few things that come close but not quite here: http://tldp.org/LDP/abs/html/arrays.html

Code:

BLOB="name=foo1 subnets=120.111.32.0/25 site=XYZ comments=this is a comment enabled=true specialCase=false"

stuff=( $BLOB )

echo ${stuff[@]/comments=/}


Keith Hedger 09-27-2013 11:33 AM

Code:

BLOB="name=foo1 subnets=120.111.32.0/25 site=XYZ comments=this is a comment enabled=true specialCase=false"
p1="${BLOB%%comments=?*}"
p2="enabled=${BLOB##?*enabled=}"
echo "$p1 $p2"

Grab a copy of the advanced bash scripting guide.

ezekieldas 09-27-2013 11:46 AM

Thanks Keith! Can you tell me what the notation BLOB%% is called? I'd like to read more about that.

I found that just this is working fine, how does ?* know to read up to "enabled"

Code:

BLOB="name=foo1 subnets=120.111.32.0/25 site=XYZ comments=this is a comment so deal with it. enabled=true specialCase=false"
stuff="${BLOB%%comments=?*}"
echo ${stuff[@]}


Keith Hedger 09-27-2013 01:12 PM

p1="${BLOB%%comments=?*}" strips the longest match of comments=?* from then end of the string giving:
name=foo1 subnets=120.111.32.0/25 site=XYZ
p2="enabled=${BLOB##?*enabled=}" strips the longest match of ?*enabled= from the front of the string giving:
enabled=true specialCase=false
"$p1 $p2" puts the back together.

"?*" matches any number of single characters.

so ?*enabled= matches "name=foo1 subnets=120.111.32.0/25 site=XYZ comments=this is a comment enabled=" and strips it.

comments=?* matches "comments=this is a comment enabled=true specialCase=false" and strips it.

All this is in the indispensable abs guide.

chrism01 09-30-2013 08:43 PM

The technique is known as 'parameter expansion'; here's a really good guide http://wiki.bash-hackers.org/syntax/pe


All times are GMT -5. The time now is 06:55 PM.