I am not sure how you want to input the string. This has the effect you want to achieve, but it might need to be modified according to how the string is entered:
aa() { echo $3 ; } ; aa "abcd efgh" "ijkl mnop" "qrst uvwxyz"
Edit: So, if it is in variable (it has to be defined with quoted ") :
AA="\"abcd efgh\" \"ijkl mnop\" \"qrst uvwxyz\""
echo $AA
then:
FIRST=`echo $AA| awk -F \" '{print $2}'`
SECOND=`echo $AA| awk -F \" '{print $4}'`
THIRD=`echo $AA| awk -F \" '{print $6}'`
echo $FIRST : $SECOND : $THIRD
as jasonwryan pointed out above. You said, you wanted to use sed, but it makes it unnecessary complex :
FIRST=`echo $AA| sed 's/^\"\([^\"]*\)\".*/\1/'`
SECOND=`echo $AA| sed 's/^\"[^\"]*\" \"\([^\"]*\)\".*/\1/'`
THIRD=`echo $AA| sed 's/^\"[^\"]*\" \"[^\"]*\" \"\([^\"]*\)\".*/\1/'`
Edit2:
It is actually possible to achieve completely without sed,awk,perl,.. only with bash, using its "read" builtin function like this (echos are for debugging):
#!/bin/bash
aa() {
echo '$1'="$1"
IFS=\" read aaa FIRST bbb SECOND ccc THIRD ddd <<< "$1"
echo FIRST=$FIRST : SECOND=$SECOND : THIRD=$THIRD
}
AA="\"abcd efgh\" \"ijkl mnop\" \"qrst uvwxyz\""
echo '$AA'="$AA"
aa "$AA"
The syntax error is self-explanatory i.e. you have used ~=
instead of =~
.
Regarding the Regex pattern, just use $pat
(and also $item
), being a shell builtin [[
can handle word splitting:
item='foobar baz'
pat=".+bar baz"
if [[ $item =~ $pat ]]; then
echo ok
fi
When you use double quotes around $pat
i.e. "$pat"
, the Regex tokens .
and +
are treated literally.
Example:
$ item='foobar baz'; pat=".+bar baz"; if [[ $item =~ $pat ]]; then echo OK; fi
OK
Best Answer
You can use
awk
to catch theip
andcountry
and save into an array:Then first element is
ip
and the next iscountry
:Or to print all elements:
Future reading: