如何替换"[1.0-4.0]"之类的字符串使用awk或sed的数值? [英] How to replace a string like "[1.0 - 4.0]" with a numeric value using awk or sed?

查看:90
本文介绍了如何替换"[1.0-4.0]"之类的字符串使用awk或sed的数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过一组awk/sed命令传递的CSV文件.

I have a CSV file that I am piping through a set of awk/sed commands.

CSV文件中的某些行如下所示:

Some lines in the CSV file look like this:

10368,"Verizon DSL",DSL,NY,NORTHEAST,-5,-4,"[1.1 - 3.0]","[0.384 - 0.768]"      

其中第8列和第9列是代表数字范围的字符串.

where the 8th and 9th columns are a string representing a numeric range.

如何使用awksed用数字值替换这些字段?范围的开始还是范围的结束?

How can I use awk or sed to replace those fields with a numeric value? Either the beginning of the range, or the end of the range?

所以这行最终会变成

10368,"Verizon DSL",DSL,NY,NORTHEAST,-5,-4,1.1,0.384      

10368,"Verizon DSL",DSL,NY,NORTHEAST,-5,-4,3.0,0.768

我到了

I got as far as removing the brackets but past that I'm stuck. I considered splitting on the " - ", but many lines in my file have a regular numeric value, not a range, in those last two columns, and that makes things messy (I don't want to end up with some lines having a different number of columns).

推荐答案

这是一个sed命令,它将采用每个范围并将其分为两个字段.它查找类似于"[A - B]"的字符串,并将其转换为A,B.如果需要,可以通过更改\1,\2部分将其轻松修改为仅使用其中一个值.该正则表达式假定所有数字在必需的小数点的两侧至少有一个数字.因此,1.53.无效.如果需要,可以使正则表达式更适应.

Here is a sed command that will take each range and break it up into two fields. It looks for strings like "[A - B]" and converts them to A,B. It can easily be modified to just use one of the values if needed by changing the \1,\2 portion. The regular expression assumes that all numbers have at least one digit on either side of a required decimal place. So, 1, .5, and 3. would not be valid. If you need that, the regex can be made to be more accommodating.

$ cat file
10368,"Verizon DSL",DSL,NY,NORTHEAST,-5,-4,"[1.1 - 3.0]","[0.384 - 0.768]"
$ sed -Ee 's|"\[([0-9]+\.[0-9]+) - ([0-9]+\.[0-9]+)\]"|\1,\2|g' file
10368,"Verizon DSL",DSL,NY,NORTHEAST,-5,-4,1.1,3.0,0.384,0.768

这篇关于如何替换"[1.0-4.0]"之类的字符串使用awk或sed的数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆