[英]Remove starting 4 letters and ending 4 letters from a file name
I would like to have a command that could strip the starting 4 letters and ending 4 letters from a filename.我想要一个命令,可以从文件名中去除开头的 4 个字母和结尾的 4 个字母。 For ex: if the file name is: form1234.tgz I would like to get the number 1234 from the file name.
例如:如果文件名是:form1234.tgz 我想从文件名中获取数字 1234。 Can someone suggest, a simple way this could be done on Linux on the command prompt?
有人可以建议,一种可以在 Linux 上的命令提示符下完成的简单方法吗?
Removing the first four characters is easy using cut
.使用
cut
可以轻松删除前四个字符。 Unfortunately, it doesn't have a built in way to remove characters from the end of a string, but you could always reverse it using rev
apply cut
and then rev
it back again.不幸的是,它没有内置的方式从字符串的结尾删除字符,但它使用你总是可以反向
rev
申请cut
,然后rev
回来了。
$ echo $FILENAME | cut -c5- | rev | cut -c5- | rev
Use parameter substitution.使用参数替换。
filename=form1234.tgz
short=${filename#????}
short=${short%????}
#
removes from the left, %
removes from the right. #
从左边移除, %
从右边移除。
You can use a lot of options actually...您实际上可以使用很多选项...
For this kind of things it would be better to match what you want instead of removing what you don't need: a typo could happen, or an already truncated file may be there...对于此类事情,最好匹配您想要的内容而不是删除您不需要的内容:可能会发生拼写错误,或者可能存在已截断的文件......
For example, if you want to get rid of the extension, you can use parameter expansion , already supported in virtually every shell:例如,如果你想摆脱扩展,你可以使用参数扩展,几乎每个 shell 都支持:
printf "%s" "${file%.*}"
If you need only numbers you can use a regular expression :如果您只需要数字,您可以使用正则表达式:
printf "%s" "${file}" | sed -e "s/.*\([0-9]*\)\..*/\1/"
Let's say that your question is way generic and does not provide a lot of information of what you want...假设您的问题很笼统,并没有提供您想要的大量信息......
If you want to statically remove the first and last 4 chars, you can use parameter expansions, sed
, cut
, awk
or whatever you want...如果你想静态删除第一个和最后 4 个字符,你可以使用参数扩展、
sed
、 cut
、 awk
或任何你想要的......
For example with sed, it would be something like:例如使用 sed,它会是这样的:
printf "%s" "${file}" | sed -e "s/^....\(.*\)....$/\1/"
With paramete expansion would be:随着参数扩展将是:
file="${file#????}"
file="${file%????}"
printf "%s" "${file}"
And finally, if you are in a pure bash environment, you can simply use some of bash parameter expansion (Note that this option will not work everywhere):最后,如果你是在纯 bash 环境中,你可以简单地使用一些 bash 参数扩展(注意这个选项不会在任何地方都有效):
printf "%s" "${file:4:-4}"
Note that every printf
could (obviusly) be replaced by echo
(or echo -n
).请注意,每个
printf
都可以(显然)被echo
(或echo -n
)替换。
Probably the easiest if you know how many chars to strip off the beginning and the end.如果您知道要去掉开头和结尾的字符数,那可能是最简单的。
name=form1234.tgz
echo "${name:4:$((${#name} - 8))}"
1234
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.