Cat last X characters on the 14th line in a file

I have a file with a line that has VERSION : X.X.X

I want to return on the console just the X.X.X part of the line. Firstly I need to get the line which I'm doing with

sed -n 14p filename.txt

I'm just a bit lost as to how I would go about returning just the last 5 characters of the line rather than the full line.

3 answers

  • answered 2020-03-25 13:29 KamilCuk

    My first thought:

    1. Reverse the line
    2. cut last/first X characters
    3. Reverse the line.

    rev | cut -c-5 | rev
    

    But with sed you can replace:

    sed 's/.*\(.\{5\}\)$/\1/'
    

  • answered 2020-03-25 13:29 Wiktor Stribiżew

    You may use

    sed -n '14 s/VERSION *: *//p' file
    

    See the online sed demo

    With s/VERSION *: *//, you will simply remove the VERSION, 0 or more spaces, :, 0 or more spaces.

  • answered 2020-03-25 13:29 RavinderSingh13

    Could you please try following.

    awk '/VERSION/{print substr($0,length($0)-4)}' Input_file
    

    Brief explanation: Looking for line which has string VERSION and then using subtr to print substring, from length-4 to till last character of line.

    On OP's question why we have to write in code length($0)-4 NOT length($0)-5: Lets understand it in following way:

    VERSION : X    .   X   .   X
              ^    ^   ^   ^   ^
              |    |   |   |   |
              -4  -3  -2   -1  Last character/letter of this line(so this becomes 1 character out of 5.
    That's why we need to mention -4 in length($0)-4 so that it takes value till last character).