Dan
Dan

Reputation: 43

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

Upvotes: 4

Views: 19604

Answers (3)

Fredrik Pihl
Fredrik Pihl

Reputation: 45634

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 

Upvotes: 0

matchew
matchew

Reputation: 19645

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>

Upvotes: 1

Beta
Beta

Reputation: 99084

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

Upvotes: 6

Related Questions