Search code examples
bashcut

Bash cut end of string with dynamic length


Perhaps my question is easy, but I can't figure out how to do this.

In a bash script I have a variable with stored snmp SysObjectID ($device_manufacturer). The values of this variable can be like:

1.3.6.1.4.1.9.1.2066
1.3.6.1.4.1.2272.9
1.3.6.1.4.1.2272.7
1.3.6.1.4.1.45.3.30.1
1.3.6.1.4.1.930.1.1
1.3.6.1.4.1.930.1.4
1.3.6.1.4.1.930.1.5

I need to cut from this value and put in another variable value starts with 1.3.6.1.4.1 and digits that goes after point and limited by point. For example:

1.3.6.1.4.1.9
1.3.6.1.4.1.2272
1.3.6.1.4.1.45

I've tried to use cut, but it returns only digits after 1.3.6.1.4.1

Please help me how to rewrite command to return right value:

unknown_device_manufacturer=$( echo $device_manufacturer0 | cut -d'.' -f7 )

Solution

  • you are close:

    unknown_device_manufacturer=$( echo $device_manufacturer0 | cut -d'.' -f1-7 )
    

    or

    unknown_device_manufacturer=$( echo $device_manufacturer0 | cut -d'.' -f-7 )
    

    From cut man page:

    N-M from N'th to M'th (included) byte, character or field

    -M from first to M'th (included) byte, character or field