Ubuntu: sed remove last 2 numerals


I have the following.

oid=. (these 0.xxx represent any random numeral)  

I want to do the following

echo $oid | sed (some commands to remove 0.xxx)  

and store the resulting string


in oid.

I don't mind this being done with Grep, awk or sed anything.
Everything before 0.xxx can change only thing static will be 0.
Thanks for your help!


With bash's Parameter expansion:

oid="."  oid="${oid%.0.*}"  echo "$oid"  




As you said this is a general form, you want to remove the last 6 characters from your text(.0.xxx), so you can use this:

echo "." |sed 's/.\{6\}$//'  

Then if you want use with variables:



echo $oid | sed 's/.\{6\}$//'  

output is:


Another solution

echo "${oid:0:${#oid}-6}"  

Another solution using cut and '.' as delimeter

echo $oid | cut -d '.' -f -10  


Using sed:

oid="$(echo -n . | sed -r 's/\.0\.[0-9]+$//')"  

-r: makes sed interpret ERE (Extended Regular Expressions) patterns

sed command breakdown:

  • s: asserts to perform a substitution
  • /: starts the pattern
  • \.: matches a . character
  • 0: matches a 0 character
  • \.: matches a . character
  • [0-9]+: matches 1 or more digits
  • $: matches the end of the line
  • /: stops the pattern / starts the replacement string
  • /: stops the replacement string / starts the modifiers


Using awk

oid="."  awk -F'.' '{for (i=2;i<=NF-2;i++) {printf "%s","."$i} }' <<< "$oid"  

or all in one

awk -F'.' '{for (i=2;i<=NF-2;i++) {printf "%s","."$i} }' <<< "."  



Short explanation

NF-2 â€" all elements without the last two elements


Using grep:

grep -Po '.*(?=\.0\.\d+$)'  

Test :

$ oid='.'    $ oid="$(grep -Po '.*(?=\.0\.\d+$)' <<<"$oid")"    $ echo "$oid"  .  
  • grep -P will enable us to use PCRE

  • grep -o will output only the matched portion

  • .*(?=\.0\.\d+$) will match all characters prior to .0, followed by . and any number of digits at the end.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »