简体   繁体   English

从ls中提取子字符串

[英]Extract substring from ls

I'm creating a little script and I have to list all my Tomcat binaries. 我正在创建一个小脚本,我必须列出我所有的Tomcat二进制文件。
So far I was able to do this: 到目前为止,我能够做到这一点:
ls -1 | grep '\\-tomcat\\-' | cut -f3 -d'-'

This basically lists all the versions, but it adds the .zip or .tar.gz 这基本上列出了所有版本,但它添加了.zip或.tar.gz

5.5.17.zip
5.5.26.tar.gz
5.5.27.tar.gz
5.5.28.tar.gz
5.5.31.tar.gz
5.5.32.tar.gz


I would like to know how to remove the .zip and .tar.gz from the extracted strings. 我想知道如何从提取的字符串中删除.zip和.tar.gz。

Or simplify the whole approach: 或者简化整个方法:

ls apache-tomcat*|sed -r 's/^.*-([0-9.]+)\..*/\1/'

Less tools, and it gives you the version numbers. 更少的工具,它为您提供版本号。

PS: Following up on @Nemo's suggestion: we let shell globbing and prior knowledge take care of half the job (just list things that actually look like apache-tomcat). PS:跟进@ Nemo的建议:我们让shell globbing和先前知识处理一半的工作(只列出实际看起来像apache-tomcat的东西)。 When piping ls' output to another tool the -1 is moot, so we get rid of that. 将ls'输出到另一个工具时,-1是没有实际意义的,所以我们摆脱了它。 sed takes the values coming from ls, matches beginning of line to the first - followed by a digit, the parenthesis remember all digits & literal periods, and then we match the rest of the string till end of line (implicit). sed获取来自ls的值,匹配行的开头到第一个 - 后跟一个数字,括号记住所有数字和文字句点,然后我们匹配字符串的其余部分直到行尾(隐式)。 And then the whole match gets replaced with the remembered digits & periods. 然后整个比赛被记住的数字和句号取代。

Pipe it through another cut : 通过另一个cut管道:

ls -1 | grep '-tomcat-' | cut -f3 -d'-' | cut -f1-3 -d'.'

This will work as long as the versions all have three components. 只要版本都有三个组件,这将有效。 If the version is just 5.5, it won't work. 如果版本只是5.5,它将无法正常工作。

Another option would be just to use sed : 另一种选择就是使用sed

ls -1 | grep '-tomcat-' | cut -f3 -d'-' | sed 's/.tar.gz\|.zip//'

This will remove .tar.gz or .zip from the strings. 这将从字符串中删除.tar.gz.zip

ls -1 | awk -F. '/-tomcat-/ {print $1}'

a solution using awk. 使用awk的解决方案。 All previous answers would work just the same. 以前的所有答案都会起作用。

EDIT: 编辑:

I may have misunderstood, perhaps this is what youre after: 我可能误解了,也许这就是你所追求的:

ls -1 | awk -F\\- '/tomcat/ {print substr($3,0,6)}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM