Stack Overflow Asked by Valentyn on September 5, 2020
I’m working on a simple awk script: awk -f file.awk test.txt
. My function:
{
split($1, arr, "[()()]")
for (i in arr) {
print(arr[i])
}
}
My test file:
1(2)V2(9)
I’m getting
1
2
V2
9
How can I get values only in brackets?
2
9
A count of values in brackets can be different.
You may get it using match
function:
awk '{s=$1; while (match(s, /([^)]*)/ )) {
print substr(s, RSTART+1, RLENGTH-2); s=substr(s, RSTART+1)}}' <<< "1(2)V2(9)"
2
9
Correct answer by anubhava on September 5, 2020
With GNU awk for multi-char RS and RT:
$ awk -v RS='[(][^)]+)' -F'[()]' '$0=RT{print $2}' file
2
9
Answered by Ed Morton on September 5, 2020
With GNU awk you can use FPAT
(field pattern) to specify how a field looks like, rather than being limited to specify a delimiter. That's handy in this case:
echo "1(2)V2(9)" |
gawk '{for(i=1;i<=NF;i++){gsub(/[()]/,"",$i);print $i}}' FPAT="[(][^)]+[)]"
2
9
Answered by hek2mgl on September 5, 2020
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP