特定格式的浮点数的 Bash 问题



(在 bash linux 中需要(我有一个包含这样的数字的文件

1.415949602
91.09582241
91.12042924
91.40270349
91.45625033
91.70150341
91.70174342
91.70660043
91.70966213
91.72597066
91.7287678315
91.7398645966
91.7542977976
91.7678146465
91.77196659
91.77299733
abcdefghij
91.7827827
91.78288651
91.7838959
91.7855
91.79080605
91.80103075
91.8050505
sed 's/^91.//' file (working) 

有什么办法可以做到这 3 个步骤吗?

第一次我试试这个

cat input | tr -d 91. > 1.txt (didnt work) 
cat input | tr -d "91." > 1.txt (didnt work) 
cat input | tr -d '91.' > 1.txt (didnt work) 

然后

grep -x '.{10}' (working)  

然后

grep "^[6-9]" (working)

最终 1 线解决方案

cat input.txt | sed 's/91.//g' | grep -x '.{10}'  | grep "^[6-9]" > output.txt

您的"最终"解决方案:

cat input.txt |
sed 's/91.//g' |
grep -x '.{10}' |
grep "^[6-9]" > output.txt

应该避免无用的cat,并将sed脚本中的反斜杠移动到正确的位置(并且我添加了一个^锚并删除了g标志,因为无论如何您不希望一行上有多个匹配项(;

sed 's/^91.//' input.txt |
grep -x '.{10}' |
grep "^[6-9]" > output.txt

你也可以摆脱至少一个无用的grep但在这一点上,我会切换到 Awk:

awk '{ sub(/^91./, "") } /^[6-9].{9}$/' input.txt >output.txt

sub()执行您的sed替换所做的操作;最后一个条件是打印与正则表达式匹配的行。

同样可以方便地用sed写,但可读性较差:

sed -n 's/^91.([6-9][0-9]{9})$/1/p' input.txt >output.txt

假设您的sed方言支持 BRE 正则表达式,重复如[0-9]{9}.

最新更新