Bash 中的字符串操作
我是 Bash 的新手,我正在做一些字符串操作。
我的目录中的其他文件中有以下文件:
jdk-6u20-solaris-i586.sh
我正在执行以下操作以在脚本中获取 jdk-6u20:
myvar=`ls -la | awk '{print $9}' | egrep "i586" | cut -c1-8`
echo $myvar
但现在我想将 jdk-6u20 转换为 jdk1.6.0_20。我似乎不知道该怎么做。
它必须尽可能通用。例如,如果我有 jdk-6u25,我应该能够以相同的方式将其转换为 jdk1.6.0_25 等等
有什么建议吗?
I am a newbie in Bash and I am doing some string manipulation.
I have the following file among other files in my directory:
jdk-6u20-solaris-i586.sh
I am doing the following to get jdk-6u20 in my script:
myvar=`ls -la | awk '{print $9}' | egrep "i586" | cut -c1-8`
echo $myvar
but now I want to convert jdk-6u20 to jdk1.6.0_20. I can't seem to figure out how to do it.
It must be as generic as possible. For example if I had jdk-6u25, I should be able to convert it at the same way to jdk1.6.0_25 so on and so forth
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
根据您想要的通用程度以及输入的标准程度,您可能可以使用
AWK
来完成所有操作。通过使用FS="regexp"
指定字段分隔符,您可以通过任何最有意义的标记分解原始字符串,并使用printf
将它们按任意顺序重新组合在一起>。例如,假设破折号和字母“u”仅用于分隔字段:
根据口味调味。
Depending on exactly how generic you want it, and how standard your inputs will be, you can probably use
AWK
to do everything. By usingFS="regexp"
to specify field separators, you can break down the original string by whatever tokens make the most sense, and put them back together in whatever order usingprintf
.For example, assuming both dashes and the letter 'u' are only used to separate fields:
Flavour according to taste.
仅使用 Bash:
Using only Bash:
我认为
is the command for you
i think that
is the command for you
你可以尝试这个片段:
You can try this snippet:
如果您想使用 if(match()),则它会取代 egrep 位。您也可以使用 substr($9,1,8) 而不是 cut 。
The if(match()) supersedes the egrep bit if you want to use it. You could use substr($9,1,8) instead of cut as well.
garph0 对 sed 有一个好主意;你可以做
garph0 has a good idea with
sed
; you could do您需要
awk
,因为ls
上有-l
开关。对于文本行的模式替换,sed
是长期的冠军:这是用“老式”sed 编写的,应该具有更好的跨平台可移植性。表达式表示:
-n
匹配,否则不要打印行您的示例变得更加简单:
You're needing the
awk
in there is an artifact of the-l
switch onls
. For pattern substitution on lines of text,sed
is the long-time champion:This was written in "old-school" sed which should have greater portability across platforms. The expression says:
-n
Your sample becomes even simpler as: