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

夙愿已清 提交于 2019-12-21 04:36:11

问题


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 to capture the last three characters in a group and replace the entire line with that group.

sed 's/^.*\(.\{3\}\)/\1/'

It works but it seems excessively verbose, especially when we compare to a method for getting the first three characters in a line.

cut -c -3

Is there a cleaner way to extract the last N characters in every line?


回答1:


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.




回答2:


rev /path/file | cut -c -3 | rev



回答3:


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



回答4:


Pure bash solution:

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

sed

$ sed 's,.*\(.\{3\}\)$,\1,'
hallo
llo
$


来源:https://stackoverflow.com/questions/24427009/is-there-a-cleaner-way-of-getting-the-last-n-characters-of-every-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!