如何从 Bash 中的字符串中删除最后 n 个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27658675/
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 remove last n characters from a string in Bash?
提问by becko
I have a variable var
in a Bash script holding a string, like:
我var
在 Bash 脚本中有一个保存字符串的变量,例如:
echo $var
"some string.rtf"
I want to remove the last 4 characters of this string and assign the result to a new variable var2
, so that
我想删除这个字符串的最后 4 个字符并将结果分配给一个新变量var2
,以便
echo $var2
"some string"
How can I do this?
我怎样才能做到这一点?
采纳答案by Mark Reed
First, you should be explicit about what you want. If you know the string ends in .rtf
and you want to remove the .rtf
, you can use var2=${var%.rtf}
. If you don't know what the suffix is but you want to remove everything after the last .
, then you can use var2=${var%.*}
. If you only want to keep everything up to the first .
, you can use var2=${var%%.*}
. Those last two options have the same result if there's only one period, but if there might be more than one, you should decide which you want.
首先,你应该明确你想要什么。如果您知道字符串以 . 结尾.rtf
并且想要删除.rtf
,则可以使用var2=${var%.rtf}
. 如果您不知道后缀是什么,但想删除最后一个 之后的所有内容.
,那么您可以使用var2=${var%.*}
. 如果您只想将所有内容保留在第一个.
,则可以使用var2=${var%%.*}
. 如果只有一个期间,后两个选项具有相同的结果,但如果可能有多个,您应该决定您想要哪个。
If you really want to always remove an exact number of characters, here are some options.
如果您真的想始终删除确切数量的字符,这里有一些选项。
You specified bash specifically, so we'll start with bash builtins. The one which has worked the longest is the same suffix-removal syntax I used above: to remove four characters, use var2=${var%????}
. You need one question mark per character removed, so this gets unwieldy for larger substring lengths.
您专门指定了 bash,因此我们将从 bash 内置函数开始。最有效的一种是我在上面使用的相同的后缀删除语法:要删除四个字符,请使用var2=${var%????}
. 您需要删除每个字符一个问号,因此对于较大的子字符串长度,这会变得笨拙。
Slightly newer is substring extraction: var2=${var::${#var}-4}
. Here you can put any number in place of the 4
to remove a different number of characters. (The ${#var}
is replaced by the length of the string, so this is actually asking to keep the first (length - 4) characters.)
稍微更新的是子字符串提取:var2=${var::${#var}-4}
. 在这里,您可以用任意数字代替4
来删除不同数量的字符。(${#var}
被字符串的长度替换,所以这实际上是要求保留第一个(长度 - 4)个字符。)
Newer versions of bash (specifically 4+, which means the one that ships with MacOS won't work) let you simplify that to just var2=${var::-4}
.
较新版本的 bash(特别是 4+,这意味着 MacOS 附带的那个将无法运行)让您将其简化为var2=${var::-4}
.
If you're not actually using bash but some other POSIX-type shell, the suffix removal will still work, even in plain old dash (where none of the rest will). In zsh, they all work but you have to put a 0
between the colons: var2=${var:0:-4}
etc. In ksh, you need the 0 and also have to use the explicit length-4 expression: var2=${var:0:${#var}-4}
.
如果您实际上不是在使用 bash,而是在使用其他一些 POSIX 类型的 shell,那么即使在普通的旧破折号中(其余的都不会),删除后缀仍然有效。在 zsh 中,它们都可以工作,但您必须0
在冒号之间放置一个:var2=${var:0:-4}
等。在 ksh 中,您需要 0 并且还必须使用显式长度 4 表达式:var2=${var:0:${#var}-4}
。
You can of course use command substitution to do it with the help of a utility program; there are plenty that will work, but something like var2=$(cut -c -4 <<<"$var")
is probably the shortest option.
您当然可以在实用程序的帮助下使用命令替换来完成此操作;有很多可以工作,但类似var2=$(cut -c -4 <<<"$var")
的可能是最短的选择。
回答by onur
You can do like this:
你可以这样做:
#!/bin/bash
v="some string.rtf"
v2=${v::-4}
echo "$v --> $v2"
回答by Etan Reisner
To remove four characters from the end of the string use ${var%????}
.
要从字符串末尾删除四个字符,请使用${var%????}
.
To remove everything after the final .
use ${var%.*}
.
最后.
使用后要删除所有内容${var%.*}
。
回答by Reut Sharabani
What worked for me was:
对我有用的是:
echo "hello world" | rev | cut -c5- | rev
# hello w
But I used it to trim lines in a file so that's why it looks awkward. The real use was:
但我用它来修剪文件中的行,所以这就是为什么它看起来很尴尬。真正的用途是:
cat somefile | rev | cut -c5- | rev
cut
only gets you as far as trimming from some starting position, which is bad if you need variable length rows. So this solution reverses (rev
) the string and now we relate to its ending position, then uses cut
as mentioned, and reverses (again, rev
) it back to it's original order.
cut
只能让您从某个起始位置进行修剪,如果您需要可变长度的行,这很糟糕。因此,此解决方案反转 ( rev
) 字符串,现在我们与它的结束位置相关联,然后cut
如上所述使用,并反转(再次rev
)将其恢复为原始顺序。
回答by fredtantini
Using Variable expansion/Substring replacement:
使用变量扩展/子串替换:
${var/%Pattern/Replacement}
If suffix of var matches Pattern, then substitute Replacement for Pattern.
${var/%Pattern/Replacement}
如果 var 的后缀匹配 Pattern,则用 Replacement 替换 Pattern。
So you can do:
所以你可以这样做:
~$ echo ${var/%????/}
some string
Alternatively,
或者,
If you have always the same 4 letters
如果你总是有相同的 4 个字母
~$ echo ${var/.rtf/}
some string
If it's always ending in .xyz
:
如果它总是以 结尾.xyz
:
~$ echo ${var%.*}
some string
You can also use the length of the string:
您还可以使用字符串的长度:
~$ len=${#var}
~$ echo ${var::len-4}
some string
or simply echo ${var::-4}
或者干脆 echo ${var::-4}
回答by Avinash Raj
You could use sed,
你可以使用sed,
sed 's/.\{4\}$//' <<< "$var"
EXample:
例子:
$ var="some string.rtf"
$ var1=$(sed 's/.\{4\}$//' <<< "$var")
$ echo $var1
some string
回答by Priya Jain
I tried the following and it worked for me:
我尝试了以下方法,它对我有用:
#! /bin/bash
var="hello.c"
length=${#var}
endindex=$(expr $length - 4)
echo ${var:0:$endindex}
Output: hel
输出: hel
回答by Siddharth Murugan
Hope the below example will help,
希望下面的例子会有所帮助,
echo ${name:0:$((${#name}-10))}
-->${name:start:len}
echo ${name:0:$((${#name}-10))}
-->${name:start:len}
- In above command, name is the variable.
start
is the string starting pointlen
is the length of string that has to be removed.
- 在上面的命令中,name 是变量。
start
是字符串的起点len
是必须删除的字符串的长度。
Example:
例子:
read -p "Enter:" name
echo ${name:0:$((${#name}-10))}
Output:
输出:
Enter:Siddharth Murugan
Siddhar
Note: Bash 4.2 added support for negative substring
注意:Bash 4.2 添加了对负子字符串的支持
回答by Greta
In this case you could use basename assuming you have the same suffix on the files you want to remove.
在这种情况下,您可以使用 basename 假设您要删除的文件具有相同的后缀。
Example:
例子:
basename -s .rtf "some string.rtf"
This will return "some string"
这将返回“一些字符串”
If you don't know the suffix, and want it to remove everything after and including the last dot:
如果您不知道后缀,并希望它删除最后一个点之后的所有内容:
f=file.whateverthisis
basename "${f%.*}"
outputs "file"
输出“文件”
% means chop, . is what you are chopping, * is wildcard
% 表示砍,。是你要砍的,* 是通配符
回答by Saurabh
This worked for me by calculating size of string.
It is easy you need to echo the value you need to return and then store it like below
这通过计算字符串的大小对我有用。
很容易你需要回显你需要返回的值,然后像下面一样存储它
removechars(){
var="some string.rtf"
size=${#var}
echo ${var:0:size-4}
}
removechars
var2=$?
some string
一些字符串