Home > Back-end >  Strip a part of string in linux
Strip a part of string in linux

Time:12-08

Apps-10.00.00R000-B1111_vm-1.0.3-x86_64.qcow2 is my string and the result I want is vm-1.0.3

What is the best way to do this

Below is what I tried

$ echo Apps-10.00.00R000-B1111_vm-1.0.3-x86_64.qcow2 | awk -F _ {'print $2'} | awk -F - {'print $1,$2'}

vm 1.0.3

I also tried

$ echo Apps-10.00.00R000-B1111_vm-1.0.3-x86_64.qcow2 | awk -F _ {'print $2'} | awk -F - {'print $1"-",$2'}

vm- 1.0.3

Here I do not need space in between

I tried using cut and I got the expected result

$ echo Apps-10.00.00R000-B1111_vm-1.0.3-x86_64.qcow2 | awk -F _ {'print $2'} | cut -c 1-8

vm-1.0.3

What is the best way to do the same?

CodePudding user response:

This is the easiest I can think of:

echo "Apps-10.00.00R000-B1111_vm-1.0.3-x86_64.qcow2" | cut -c 25-32

Obviously you need to be sure about the location of your characters. In top of that, you seem to be have two separators: '_' and '-', while both characters also are part of the name of your entry.

CodePudding user response:

echo 'Apps-10.00.00R000-B1111_vm-1.0.3-x86_64.qcow2' | sed -E 's/^.*_vm-([0-9] ).([0-9] ).([0-9] )-.*/vm-\1.\2.\3/'

CodePudding user response:

echo 'Apps-10.00.00R000-B1111_vm-1.0.3-x86_64.qcow2' |
sed -E 's/^.*_vm-([0-9] ).([0-9] ).([0-9] )-.*/vm-\1.\2.\3/'

CodePudding user response:

This is what I came up with. It's better to use a single program instead of running two different programs simultaneously

echo "Apps-10.00.00R000-B1111_vm-1.0.3-x86_64.qcow2" | cut -c 25-32

CodePudding user response:

Making assumptions from the 1 example you provided about what the general form of your input will be so it can handle that robustly, using any sed:

$ echo 'Apps-10.00.00R000-B1111_vm-1.0.3-x86_64.qcow2' |
    sed 's/^[^-]*-[^-]*-[^_]*_\(.*\)-[^-]*$/\1/'
vm-1.0.3

or any awk:

$ echo 'Apps-10.00.00R000-B1111_vm-1.0.3-x86_64.qcow2' |
    awk 'sub(/^[^-] -[^-] -[^_] _/,"") && sub(/-[^-] $/,"")'
vm-1.0.3
  • Related