LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Substring of string in tag + shell script (https://www.linuxquestions.org/questions/linux-newbie-8/substring-of-string-in-tag-shell-script-786900/)

linux_man 02-04-2010 04:17 AM

Substring of string in tag + shell script
 
Hi,

Please help me solve the following as I am new to scripting

I have a string variable

var1=<default>111</default>

I want the value between default tags 111 in this case.

I treid to use ${var1:10:3}
But the execution gived "bad substitution' error.

If the tags are removed and substring is fetched it works fine.
Please help me.
Is there any other was to get substring in a string with tags.
Thanks i advance

AngTheo789 02-04-2010 04:42 AM

Indexing is zerobased, so it should be ${var:9:3}. Otherwise it works on my bash shell.

catkin 02-04-2010 04:54 AM

You need quotes to assign the string:
Code:

c:~$ var1=<default>111</default>
bash: syntax error near unexpected token `111'

Now with quotes and showing a way to parse the value from between the tags
Code:

c:~$ var1='<default>111</default>'
c:~$ var1="${var1#<default>}"
c:~$ var1="${var1%</default>}"
c:~$ echo $var1
111


AngTheo789 02-04-2010 05:58 AM

Quotes are needed indeed!

linux_man 02-04-2010 09:04 PM

Thanks for ur reply...

Can you please tell me a way to extract 111 from <default>111</default> using SED command.
I do not want to hard code the character position to get the value.

catkin 02-04-2010 10:32 PM

Quote:

Originally Posted by linux_man (Post 3853308)
I do not want to hard code the character position to get the value.

The technique shown above using bash parameter expansion does not hard code the character position and runs faster than using sed.


All times are GMT -5. The time now is 09:40 AM.