简体   繁体   中英

awk sed filter values in all lines greater/smaller than

is there a way to construct a filter in awk (or something similar) that for a given file, say:

0.99,0.98,1.1,0.85,0.92
0.76,1.4,0.99,0.99,0.82
1.0,1.45,0.78,0.91,0.95

would replace any record in a line that is greater than 1.0 with 1.0?

Here is something you can do with awk

awk -F, '{for(i=1;i<=NF;i++) if($i>1) {$i="replacement"}}1' OFS=, file

Test:

$ cat file
0.99,0.98,1.1,0.85,0.92
0.76,1.4,0.99,0.99,0.82
1.0,1.45,0.78,0.91,0.95

$ awk -F, '{for(i=1;i<=NF;i++) if($i>1) {$i="replacement"}}1' OFS=, file
0.99,0.98,replacement,0.85,0.92
0.76,replacement,0.99,0.99,0.82
1.0,replacement,0.78,0.91,0.95

Here's a sed solution:

sed -e 's/[1-9][0-9]*\.[0-9]*/1.0/g' in-file > out-file

The pattern [1-9][0-9]*\\.[0-9]* simply matches any sequence that begins with a digit greater than 0 , followed by zero or more digits, followed by the decimal point, followed by additional digits. If you want an in-place replacement, you can use the -i option:

sed -i -e 's/[1-9][0-9]*\.[0-9]*/1.0/g' in-file

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