开发者

How do I use sed to remove decimal numbers from a string?

I have the following string as an example: ex. "Abandoned 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"

I was using the following command: sed 's/.//g' which apparently doesn't work.

Can someone let me know how to use the wildcard character with sed to remove anything matching ".".

Thanks开发者_如何学编程


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/ *$//'


this would be easier with awk, at least for me

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'

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

Why catch the white sapce? well imagine if 16 came after 3.50 in your example you would then return

Abandoned [5spaces*] 16 *I can only insert one space in this <textarea>


Trowing in a awk solution that loops ovewr the input and skips entries with a period in them

{
     printf("%s ", $1)
     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 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜