Ubuntu: sed remove last 2 numerals



Question:

I have the following.

oid=.1.3.6.1.4.1.795.2.5.0.xxx (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

.1.3.6.1.4.1.795.2.5  

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!


Solution:1

With bash's Parameter expansion:

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

Output:

  .1.3.6.1.4.1.795.2.5  


Solution:2

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 ".1.3.6.1.4.1.795.2.5.0.xxx" |sed 's/.\{6\}$//'  

Then if you want use with variables:

oid=.1.3.6.1.4.1.795.2.5.0.xxx  

Then:

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

output is:

.1.3.6.1.4.1.795.2.5  

Another solution

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

Another solution using cut and '.' as delimeter

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


Solution:3

Using sed:

oid="$(echo -n .1.3.6.1.4.1.795.2.5.0.0 | 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


Solution:4

Using awk

oid=".1.3.6.1.4.1.795.2.5.0.xxx"  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} }' <<< ".1.3.6.1.4.1.795.2.5.0.xxx"  

Output

.1.3.6.1.4.1.795.2.5  

Short explanation

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


Solution:5

Using grep:

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

Test :

$ oid='.1.3.6.1.4.1.795.2.5.0.908'    $ oid="$(grep -Po '.*(?=\.0\.\d+$)' <<<"$oid")"    $ echo "$oid"  .1.3.6.1.4.1.795.2.5  
  • 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
Previous
Next Post »