简体   繁体   English

Bash读取文件名并使用awk返回版本号

[英]Bash read filename and return version number with awk

I am trying to use one or two lines of Bash (that can be run in a command line) to read a folder-name and return the version inside of the name. 我正在尝试使用Bash的一两行(可以在命令行中运行)来读取文件夹名称并返回名称内的版本。

So if I have myfolder_v1.0.13 I know that I can use echo "myfolder_v1.0.13" | awk -F"v" '{ print $2 }' 因此,如果我拥有myfolder_v1.0.13我知道可以使用echo "myfolder_v1.0.13" | awk -F"v" '{ print $2 }' echo "myfolder_v1.0.13" | awk -F"v" '{ print $2 }' and it will return with 1.0.13 . echo "myfolder_v1.0.13" | awk -F"v" '{ print $2 }' ,它将返回1.0.13

But how do I get the shell to read the folder name and pipe with the awk command to give me the same result without using echo ? 但是,如何使用awk命令使外壳读取文件夹名称和管道,以在不使用echo情况下提供相同的结果? I suppose I could always navigate to the directory and translate the output of pwd into a variable somehow? 我想我总是可以导航到该目录并将pwd的输出以某种方式转换为变量?

Thanks in advance. 提前致谢。

Edit: As soon as I asked I figured it out. 编辑:一问到我就想通了。 I can use 我可以用

result=${PWD##*/}; echo $result | awk -F"v" '{ print $2 }'

and it gives me what I want. 它给了我我想要的 I will leave this question up for others to reference unless someone wants me to take it down. 我将把这个问题留给他人参考,除非有人要我把它取下来。

But you don't need an Awk at all, here just use bash parameter expansion. 但是您根本不需要Awk ,只需使用bash参数扩展即可。

string="myfolder_v1.0.13"
printf "%s\n" "${string##*v}"
1.0.13

You can use 您可以使用

basename "$(cd "foldername" ; pwd )" | awk -Fv '{print $2}'

to get the shell to give you the directory name, but if you really want to use the shell, you could also avoid the use of awk completetly: Assuming you have the path to the folder with the version number in the parameter "FOLDERNAME": 以获得外壳程序的目录名称,但是如果您确实要使用外壳程序,则还可以完全避免使用awk:假设您在参数“ FOLDERNAME”中具有版本号的文件夹的路径:

echo "${FOLDERNAME##*v}"

This removes the longest prefix matching the glob expression "*v" in the value of the parameter FOLDERNAME. 这将删除与参数FOLDERNAME的值中的全局表达式“ * v”匹配的最长前缀。

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

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