Reputation: 43558
I have string looks likes this
string="xxxxx.yyyyy[2].zzzzz"
I want to extract the number between the [ ]
. I used the following awk
command
echo $string | awk -F'[]' '{print $2}'
But this awk
command returns error:
awk: bad regex '[]': Unmatched [ or [^
How to fix that?
Upvotes: 2
Views: 998
Reputation: 41460
Here is a more generic approach. It will get any number out of a text file:
echo "xxxxx.yyyyy[2].zzzzz" | awk -F "[^0-9]*" '{for (i=2;i<=NF;i++) printf "%s%s",$i,(i==NF?RS:" ")}'
2
Other example
cat file
"C 56","Home athletics center","LAC"
"D001","50M Run","50M"
"D003","10.505M Run","100M","42K"
awk -F "[^0-9.]*" '{for (i=2;i<=NF;i++) printf "%s%s",$i,(i==NF?RS:" ")}' file
56
001 50 50
003 10.505 100 42
Upvotes: 0
Reputation: 5298
With sed:
echo "xxxxx.yyyyy[2].zzzzz" | sed -r 's/.*\[(.*)\].*/\1/g'
With awk:
echo "xxxxx.yyyyy[2].zzzzz" | awk 'BEGIN {FS="[";RS="]"} {print $2}'
Upvotes: 0
Reputation: 785856
This should work:
echo "xxxxx.yyyyy[2].zzzzz" | awk -F '[][]' '{print $2}'
2
Order of ]
before [
inside character class is important here.
This shall also work by double escaping [
and ]
using alternation regex:
echo "xxxxx.yyyyy[2].zzzzz" | awk -F '\\[|\\]' '{print $2}'
2
OR:
echo "xxxxx.yyyyy[2].zzzzz" | awk -F '[\\[\\]]' '{print $2}'
2
Upvotes: 6