Multiple field separators in awk

I have this line

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

I want to divide it into numbers and iterate over them, thanks tried to use the field separator without success, how can I do this with awk?

+8
string regex awk
source share
4 answers

Try to do this:

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

The FS field separator (switch -F ) can be a character, word, regular expression, or character class.

You can also use this:

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

explanations

  • foo|bar|base is a regular expression in which it can match any of the lines separated by |
  • in }+|{+| , we can choose a literal } at least one: + or a literal { at least one: + or a space.
  • you can also use a character class to do the same: [{} ] , both work
+14
source share

One way with awk:

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

In the line above, we looked at these numbers, but I did not do anything special, I just printed them. You can add your own logic to this part.

Exit:

 0.000 0.000 648.0 0.000 648.0 1980.0 0.000 1980.0 0.000 0.000 
+1
source share

If you just want to display each number on a new line, just 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 
+1
source share

Admittedly, I am very simple in my suggestion. In my experience, examples of regular expressions for a 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 faced with characters that do not matter. A simple fix is ​​to simply remove unnecessary characters. There are various ways, but I would use tr -d '{}' as follows:

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

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

0
source share

All Articles