Shell脚本将字符串从一种形式转换为另一种形式 [英] Shell script to convert a string from one form to another
问题描述
我有两个字符串
internal func add(a: Int, b: Int) -> Int
add(a:b:)
如何使第一个字符串转换为第二个字符串.我可以使用编程语言来做到这一点,但无法找到我所需的bash脚本解决方案.
How can I make the first string convert into the second string. I can do this in programming languages, but unable to figure out a solution for bash script that I need.
基本上,所需的是func
(包括)func
之前的所有内容,并且->
(包括)->
之后的所有内容都应该删除,变量的类型也应该删除.所有空格也应该消失.
Essentially whats needed is anything before (and including) func
should be trimmed and anything following (and including) ->
should be removed and the type of variables should be removed. All spaces should also go.
此外,我尝试使用正则表达式.我做了(?:.*func\s(.*)\s->.*)
,它从第一个字符串中取出了add(a: Int, b: Int)
,但是,我不确定如何进一步消除该字符串.
Also, I tried using regex. I made (?:.*func\s(.*)\s->.*)
that takes out the add(a: Int, b: Int)
from the 1st string, but, I am not sure, how to further eliminate this string.
我最好在使用awk或sed的bash方面需要一些帮助,但是regex对我也很好.
I preferably need some help in bash using awk or sed but regex would also do well for me.
推荐答案
使用SED:
string='internal func add(a: Int, b: Int) -> Int'
sed -e '
s/^.*func \+//
s/ *\->.*$//
s/:[^,)]\+/:/g
s/[, ]//g
' <<< "$string"
-
s/^.*func \+//
删除func
,func
之前的前(^
)部分,并删除func
之后的空格; -
s/ *\->.*$//
删除空格,后跟->
以及字符串末尾的任何内容; -
s/:[^,)]\+/:/g
删除冒号后的类型名称; -
s/[, ]//g
通过删除逗号和空格来执行最终清除. s/^.*func \+//
removes the front (^
) part beforefunc
,func
, and spaces afterfunc
;s/ *\->.*$//
removes spaces followed by->
and anything after it at the end of the string;s/:[^,)]\+/:/g
removes the type names after colons;s/[, ]//g
performs final cleanup by removing commas and spaces.
这篇关于Shell脚本将字符串从一种形式转换为另一种形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!