Extract substring from ls

I am creating a little script and I need to list all my Tomcat binaries.
So far, I could do this:
ls -1 | grep '\-tomcat\-' | cut -f3 -d'-'

This is basically a list of all versions, but it adds .zip or .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 .zip and .tar.gz from the extracted lines.

+4
source share
3 answers

Or simplify the whole approach:

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

Less tools and it gives you version numbers.

PS: Following @Nemo's recommendations: we let the globbing shell and prior knowledge take care of half the work (just list things that actually look like apache-tomcat). When piping ls' is output to another tool, -1 is debatable, so we get rid of it. sed accepts values ​​from ls that match the beginning of the line to the first, followed by a digit, the bracket remembers all the numbers and letter periods, and then we map the rest of the line to the end of the line (implicit). And then the whole match is replaced by catchy numbers and periods.

+5
source

Pull it through another cut :

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

This will work as long as all versions have three components. If the version is only 5.5, this will not work.

Another option is to just use sed :

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

This will remove .tar.gz or .zip from the lines.

+4
source

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

awk solution. All previous answers will work the same.

EDIT:

Perhaps I misunderstood, perhaps this is what you are after:

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

+1
source

All Articles