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

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

Pipe out a substring by removing the last N characters

bashunix

提问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 nis number of characters you want to shave from end

n你想从最后剃掉的字符数在哪里

echo "forbes" | rev | cut -c 4- | rev
for

回答by mklement0

GNU headis another option (remove the last ncharacters 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 echoinstead of printf, there's a trailing \nthat must be taken into account, so you must add 1to the count (and the output won't have a trailing \n).

请注意,如果您使用echo代替printf,则\n必须考虑尾随,因此您必须添加1到计数中(并且输出不会有尾随\n)。

Caveat:head -coperates on bytes, and therefore only works with ASCII characters and other single-byte encodings.

警告:head -cbytes 进行操作,因此仅适用于 ASCII 字符和其他单字节编码。

回答by mklement0

An awksolution (removes the last ncharacters 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 awkimplementations are locale-aware; for instance, BSD awkas found on OS X 10.11.4 is not:

警告:并非所有的awk实现都可以识别区域设置;例如,awk在 OS X 10.11.4 上发现的BSD不是:

##代码##