Is there a cleaner way of getting the last N characters of every line?

后端 未结 4 1744
轮回少年
轮回少年 2020-12-30 08:27

To simplify the discussion, let N = 3.

My current approach to extracting the last three characters of every line in a file or stream is to use sed

相关标签:
4条回答
  • 2020-12-30 08:59

    Pure bash solution:

    $ while read -r in; do echo "${in: -3}"; done
    hello
    llo
    $
    

    sed

    $ sed 's,.*\(.\{3\}\)$,\1,'
    hallo
    llo
    $
    
    0 讨论(0)
  • 2020-12-30 09:00
    rev /path/file | cut -c -3 | rev
    
    0 讨论(0)
  • 2020-12-30 09:21

    It's very simple with grep -o '...$':

    cat /etc/passwd  | grep -o '...$'
    ash
    /sh
    /sh
    /sh
    ync
    /sh
    /sh
    /sh
    

    Or better yer:

    N=3; grep -o ".\{$N\}$" </etc/passwd
    ash
    /sh
    /sh
    /sh
    ync
    /sh
    /sh
    

    That way you can adjust your N for whatever value you like.

    0 讨论(0)
  • 2020-12-30 09:22

    Why emphasize brevity when it's a tiny command either way? Generality is much more important:

    $ cat file
    123456789
    abcdefghijklmn
    

    To print 3 characters starting from the 4th character:

    $ awk '{print substr($0,4,3)}' file
    456
    def
    

    To print 3 characters starting from the 4th-last character:

    $ awk '{print substr($0,length($0)-3,3)}' file
    678
    klm
    

    To print 3 characters from [around] the middle of each line:

    $ awk '{print substr($0,(length($0)-3)/2,3)}' file
    345
    efg
    
    0 讨论(0)
提交回复
热议问题