AnswerBun.com

Get only values in brackets after row splitting using awk

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.

3 Answers

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

See: Defining fields by content

Answered by hek2mgl on September 5, 2020

Add your own answers!

Related Questions

Can i show all variable results in a div in jQuery?

0  Asked on December 5, 2021 by nippledisaster

   

Comparing two generics in compareTo()

2  Asked on December 5, 2021 by chalupabatmac

       

arranging the json file base on key value

1  Asked on December 5, 2021 by prateek-singh

     

Vue watch method not filtering object

3  Asked on December 5, 2021

   

Passing a variable between HTML pages using JavaScript

2  Asked on December 5, 2021 by robert-little

   

How to avoid code redundancy with JAVA generics

1  Asked on December 5, 2021 by cosimoth

   

Why is my project no longer updating when I write new code?

1  Asked on December 5, 2021 by stephen-horton

       

node https ssl your connection is not private error

2  Asked on December 5, 2021 by andrea-dattero

       

Nested for loop using dict

9  Asked on December 5, 2021 by purwu

     

React Hooks – Input loses focus when 1 character is typed in

4  Asked on December 5, 2021 by dragos-strugar

   

How do I build a C Python Extension for Windows using Cygwin64?

2  Asked on December 5, 2021 by zenith2198

       

Wificonfiguration is deprecated Android 10

1  Asked on December 5, 2021 by ahmad-idrees

         

Wrong tootip in chartjs

1  Asked on December 5, 2021 by thiago-scher

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP