bash 如何在bash字符串切割中切割字符串的最后n个字节?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1030489/
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
how to chop last n bytes of a string in bash string choping?
提问by jaimechen
for example qa_sharutils-2009-04-22-15-20-39, want chop last 20 bytes, and get 'qa_sharutils'.
例如qa_sharutils-2009-04-22-15-20-39,想要砍掉最后 20 个字节,然后得到“ qa_sharutils”。
I know how to do it in sed, but why $A=${A/.\{20\}$/}does not work?
我知道如何在 sed 中做到这一点,但为什么$A=${A/.\{20\}$/}不起作用?
Thanks!
谢谢!
回答by Charles Ma
If your string is stored in a variable called $str, then this will get you give you the substring without the last 20 digits in bash
如果您的字符串存储在名为 $str 的变量中,那么这将使您在 bash 中为您提供没有最后 20 位数字的子字符串
${str:0:${#str} - 20}
basically, string slicing can be done using
基本上,字符串切片可以使用
${[variableName]:[startIndex]:[length]}
and the length of a string is
一个字符串的长度是
${#[variableName]}
EDIT: solution using sed that works on files:
编辑:使用适用于文件的 sed 的解决方案:
sed 's/.\{20\}$//' < inputFile
回答by Gabriel G
using awk:
使用 awk:
echo $str | awk '{print substr(echo ${str:0:$((${#str}-20))}
,1,length(echo 'abcdefg'|tail -c +2|head -c 3
)-20)}'
or using strings manipulation - echo ${string:position:length}:
或使用字符串操作 - echo ${string:position:length}:
$ str="qa_sharutils-2009-04-22-15-20-39"
回答by diyism
similar to substr('abcdefg', 2-1, 3) in php:
类似于 php 中的 substr('abcdefg', 2-1, 3) :
$ echo ${str::${#str}-20}
qa_sharutils
回答by John Kugelman
In the ${parameter/pattern/string}syntax in bash, patternis a path wildcard-style pattern, not a regular expression. In wildcard syntax a dot .is just a literal dot and curly braces are used to match a choice of options (like the pipe |in regular expressions), so that line will simply erase the literal string ".20".
在${parameter/pattern/string}bash的语法中,pattern是路径通配符样式的模式,而不是正则表达式。在通配符语法中,点.只是一个文字点,大括号用于匹配选项的选择(如|正则表达式中的管道),因此该行将简单地擦除文字 string ".20"。
回答by Stan Graves
There are several ways to accomplish the basic task.
有几种方法可以完成基本任务。
$ echo ${str%%-*}
qa_sharutils
If you want to strip the last 20 characters. This substring selection is zero based:
如果你想去掉最后 20 个字符。此子字符串选择是基于零的:
$ str="qa_sharutils-2009-04-22-15-20-39"
$ IFS="-"
$ set -- $str
$ echo
qa_sharutils
$ unset IFS
The "%" and "%%" to strip from the right hand side of the string. For instance, if you want the basename, minus anything that follows the first "-":
从字符串的右侧剥离的“%”和“%%”。例如,如果您想要基本名称,减去第一个“-”之后的任何内容:
$ echo ${str%%-*}
qa_sharutils
回答by ghostdog74
only if your last 20 bytes is always date.
仅当您的最后 20 个字节始终是日期时。
##代码##or when first dash and beyond are not needed.
或者当不需要第一次破折号时。
##代码##
