Reputation: 113
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?
Upvotes: 11
Views: 28484
Reputation: 195059
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
Upvotes: 1
Reputation: 1
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
)
Upvotes: 0
Reputation: 85785
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
Upvotes: 1
Reputation: 185126
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
foo|bar|base
is a regex where it can match any of the strings separated by the |
}+|{+|
, we have the choice to match a literal }
at least one : +
, or a literal {
at least one : +
, or a space.[{} ]
, both worksUpvotes: 18