bash 有没有更简洁的方法来获取每行的最后 N 个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24427009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:44:55  来源:igfitidea点击:

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

bashcommand-lineawksedcut

提问by merlin2011

To simplify the discussion, let N = 3.

为了简化讨论,让N = 3

My current approach to extracting the last three characters of every line in a file or stream is to use sedto capture the last three characters in a group and replace the entire line with that group.

我当前提取文件或流中每一行的最后三个字符的方法是使用sed捕获组中的最后三个字符并将整行替换为该组。

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

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

它有效但似乎过于冗长,尤其是当我们与获取一行中的三个字符的方法进行比较时。

cut -c -3

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

有没有更简洁的方法来提取每行的最后 N 个字符?

回答by Tiago Lopo

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

这非常简单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 Nfor whatever value you like.

这样你就可以调整N你喜欢的任何值。

回答by Cyrus

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

回答by Ed Morton

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:

从第 4 个字符开始打印 3 个字符:

$ awk '{print substr(
$ awk '{print substr(
$ awk '{print substr(
$ while read -r in; do echo "${in: -3}"; done
hello
llo
$
,(length(
$ sed 's,.*\(.\{3\}\)$,,'
hallo
llo
$
)-3)/2,3)}' file 345 efg
,length(##代码##)-3,3)}' file 678 klm
,4,3)}' file 456 def

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

从倒数第 4 个字符开始打印 3 个字符:

##代码##

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

要从每行中间的 [周围] 打印 3 个字符:

##代码##

回答by lx42.de

Pure bash solution:

纯 bash 解决方案:

##代码##

sed

sed

##代码##