Search code examples
unixawksedgreptail

Grep last N characters of each line in a file


I have a file with millions of lines.And each line ends with a format say "XXX:some value" .. I want to grep only this word "XXX:some value" from each line and put it in a separate file.How can i achieve this using grep command?

PS: "some value" can be any string


Solution

  • To get last n characters of each line using awk:

    cat file
    asdf
    asdfg
    asdfgh
    

    awk -vn=2 '{print substr($0,length($0)-n+1)}'
    df
    fg
    gh
    

    Or do you like to get data after XXX, then do:

    echo "here is my line XXX:22" | awk -F"XXX:" '{print $2}'
    22