简体   繁体   中英

multiple Field Separators in awk

i have this string

-foo {{0.000 0.000} {648.0 0.000} {648.0 1980.0} {0.000 1980.0} {0.000 0.000}}

i want to separate it to numbers and iterate over them ,thanks tried to use Field separator without success how can i do it with awk?

Try doing this :

awk -F'}+|{+| ' '{for (i=1; i<=NF; i++) if ($i ~ "[0-9]") print $i}' file.txt

The Field Separator FS (the -F switch) can be a character, a word, a regex or a class of characters.

You can use this too :

awk 'BEGIN{FS="}+|{+| "} {for(i=1;i<=NF;i++) if($i ~ "[0-9]")print $i}' file.txt

explanations

  • foo|bar|base is a regex where it can match any of the strings separated by the |
  • in }+|{+| , we have the choice to match a literal } at least one : + , or a literal { at least one : + , or a space.
  • you can use a class of character too to do the same : [{} ] , both works

One way with awk :

awk -F'[{} ]' '{ for( i=1; i<=NF; i++ ) if( $i ~ /[0-9.]+/ ) print $i }' file

In the line above, we went through those numbers, but I didn't do anything special, just printed them. You could add your logic to that part.

Output:

0.000
0.000
648.0
0.000
648.0
1980.0
0.000
1980.0
0.000
0.000

If you just want to display each number on a new line then simply use grep :

$ egrep -o '[0-9]+\.[0-9]+' file
0.000
0.000
648.0
0.000
648.0
1980.0
0.000
1980.0
0.000
0.000

Admittedly, I am being very simple-minded in my offering. In my experience, the regex examples for the field separator are the most valuable to learn, especially if you have to deal with XML, etc. But in this case, we must remember that UNIX gives you many alternatives when confronted with characters that are irrelevant. A simple fix is to just remove the unwanted characters. There are various ways, but I would use tr -d '{}' like so:

tr -d '{}' file.txt | awk '{ for( i=2; i<=NF; i++ ) print $i }'

Starting the loop counter i at 2 is just a quick way to skip the first argument ( -foo )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM