Search code examples
unixcut

Unix cut command to extract string from left side post 2nd dilimiter from right


how can the cut command return value left to 2nd last delimiter starting from the right side.

$ echo 'qwertyuiop.abcdefgh.1234567890.txt' | cut -d '.' -f 1,2
qwertyuiop.abcdefgh
$ echo 'qwertyuiop.1234567890.txt' | cut -d '.' -f 1,2
qwertyuiop.1234567890
$ 

expected output for both

qwertyuiop.abcdefgh

qwertyuiop


Solution

  • You can reverse your string with the rev command and then cut from the third field to the end, reversing at the end.

    $ echo 'qwertyuiop.abcdefgh.1234567890.txt' | rev | cut -d '.' -f 3- | rev
    qwertyuiop.abcdefgh
    $ echo 'qwertyuiop.1234567890.txt' | rev | cut -d '.' -f 3- | rev
    qwertyuiop