bash 通过删除最后 N 个字符来输出子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36852819/
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
Pipe out a substring by removing the last N characters
提问by iLemming
How can I pipe a string and drop a few characters off it?, e.g:
如何通过管道传输字符串并从中删除几个字符?,例如:
$ echo forbes | ... -3
for
$ echo cucumber | ... -4
cucu
$ echo 1461624333 | .. -3
1461624
...
etc.
I couldn't find way to use ${str:0:-3}
syntax in a pipe.
我找不到${str:0:-3}
在管道中使用语法的方法。
回答by Benjamin W.
Piping to sed:
管道到 sed:
$ echo forbes | sed 's/...$//'
for
This matches the last three characters of the string and removes them (substitutes with the empty string).
这匹配字符串的最后三个字符并删除它们(用空字符串替换)。
To parametrize the number of characters to remove, we can wrap this in a little function:
要参数化要删除的字符数,我们可以将其包装在一个小函数中:
pipesubstr () {
sed "s/.\{\}$//"
}
to be used as follows:
用途如下:
$ echo forbes | pipesubstr 3
for
$ echo cucumber | pipesubstr 4
cucu
$ echo 1461624333 | pipesubstr 3
1461624
回答by jaypal singh
Use cut
?
使用cut
?
$ echo "forbes" | cut -b 1-3
for
Update:
更新:
To shave from behind, you can do:
要从后面剃须,您可以执行以下操作:
echo "forbes" | rev | cut -c (n+1)- | rev
where n
is number of characters you want to shave from end
n
你想从最后剃掉的字符数在哪里
echo "forbes" | rev | cut -c 4- | rev
for
回答by mklement0
GNU head
is another option (remove the last n
characters from the input string as a whole- even if it spans multiple lines):
GNUhead
是另一种选择(删除最后一个n
从输入字符串中的字符作为一个整体-即使它跨越了多个行):
$ printf '1461624333' | head -c -3 # drop last 3 chars.
1461624
Note that if you use echo
instead of printf
, there's a trailing \n
that must be taken into account, so you must add 1
to the count (and the output won't have a trailing \n
).
请注意,如果您使用echo
代替printf
,则\n
必须考虑尾随,因此您必须添加1
到计数中(并且输出不会有尾随\n
)。
Caveat:head -c
operates on bytes, and therefore only works with ASCII characters and other single-byte encodings.
警告:head -c
对bytes 进行操作,因此仅适用于 ASCII 字符和其他单字节编码。
回答by mklement0
An awk
solution (removes the last n
characters from every linein the input):
一个awk
解决方案(从输入的每一行中删除最后一个n
字符):
$ echo '1461624333' | awk -v n=3 '{ print substr($ echo 'us?' | awk -v n=1 '{ print substr(##代码##, 1, length(##代码##)-n) }'
us? # !! on OSX, mistakenly returns the first byte of multi-byte UTF8 char. '?'
, 1, length(##代码##)-n) }' # drop last 3
1461624
Caveat:Not all awk
implementations are locale-aware; for instance, BSD awk
as found on OS X 10.11.4 is not:
警告:并非所有的awk
实现都可以识别区域设置;例如,awk
在 OS X 10.11.4 上发现的BSD不是: