Linux 如何使用 sed 从字符串中删除十进制数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6512620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use sed to remove decimal numbers from a string?
提问by Dan
I have the following string as an example: ex. "Abandoned 16 1.10 2.62 3.50"
我以以下字符串为例:ex。《废弃16 1.10 2.62 3.50》
I would like to pipe this result to sed and remove all decimal numbers to leave me with the following: ex. "Abandoned 16"
我想将此结果通过管道传输到 sed 并删除所有十进制数字,以留下以下内容:例如。《被遗弃的16》
I was using the following command: sed 's/.//g' which apparently doesn't work.
我正在使用以下命令: sed 's/ 。//g' 显然不起作用。
Can someone let me know how to use the wildcard character with sed to remove anything matching ".".
有人可以让我知道如何在 sed 中使用通配符来删除任何匹配“ .”的内容。
Thanks
谢谢
采纳答案by Beta
You haven't said what you want to do with the whitespace, but how about
你还没有说你想用空格做什么,但是怎么样
sed -e 's/[0-9]*\.[0-9]*//g' -e 's/ *$//'
回答by matchew
this would be easier with awk
, at least for me
这会更容易awk
,至少对我来说
echo "Abandoned 16 1.10 2.62 3.50" | awk '{print $1FS$2}'
echo "Abandoned 16 1.10 2.62 3.50" | awk '{print $1FS$2}'
but is the list of numbers random afterwards?
但是之后的数字列表是随机的吗?
if so, this works too
如果是这样,这也有效
echo "Abandoned 16 1.10 2.62 3.50" | sed -r 's/\s([0-9]+)\.([0-9]+)//g'
echo "Abandoned 16 1.10 2.62 3.50" | sed -r 's/\s([0-9]+)\.([0-9]+)//g'
note that \s
catches the white space, and that the numbers before and after the decimal are saved, so if you want to retain them and do something with them you can access them with \1
and \2
respectfully
需要注意的是\s
抓住了空白,而且小数点前后的编号保存,所以如果你想留住他们,并与他们做的东西你可以访问它们\1
,并\2
恭敬地
Why catch the white sapce? well imagine if 16 came after 3.50 in your example you would then return
为什么要抓住白点?想象一下,如果 16 在您的示例中出现在 3.50 之后,那么您将返回
Abandoned [5spaces*] 16
*I can only insert one space in this <textarea>
Abandoned [5spaces*] 16
*我只能在这里插入一个空格 <textarea>
回答by Fredrik Pihl
Trowing in a awk solution that loops ovewr the input and skips entries with a period in them
使用 awk 解决方案,循环覆盖输入并跳过其中包含句点的条目
{
printf("%s ", )
for(i=2;i<NF;i++) {
if ($i !~ /\./) {
printf( " %s ", $i)
}
}
}
$ echo Abandoned 16 1.10 2.62 3.50 | awk -f f.awk
Abandoned 16