Reputation: 3927
I have two strings
internal func add(a: Int, b: Int) -> Int
add(a:b:)
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.
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.
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.
I preferably need some help in bash using awk or sed but regex would also do well for me.
Upvotes: 1
Views: 466
Reputation: 257
This is another sed
approach to problem:
sed -r 's/^.*internal func *(\w+)\(([^)]*)\).*$/\1(\2)/;ta;b;:a;s/*(\w+:) *\w+,*/\1/g'
Upvotes: -2
Reputation: 85800
A solution in perl
regEx
as
perl -lne 'print "$1$2$3)" if /^.*func (\w+)(\(\w+:).*, (\w+:).*\).*$/ ' <<<"internal func add(a: Int, b: Int) -> Int"
add(a:b:)
where, $1
, $2
and $3
are the capturing groups and a small hack with printing )
at end.
If your shell does not support here-strings(<<<)
, just do
echo "internal func add(a: Int, b: Int) -> Int" | perl -lne 'print "$1$2$3)" if /^.*func (\w+)(\(\w+:).*, (\w+:).*\).*$/ '
add(a:b:)
Upvotes: 1
Reputation: 5714
Using pure bash in "oneliner" style:
#!/bin/bash
str="internal func add(a: Int, b: Int) -> Int"
[[ $str =~ .*func[[:space:]](.*\(.*:).*,[[:space:]]?(.*:).*(\)) ]] && str="${BASH_REMATCH[1]}${BASH_REMATCH[2]}${BASH_REMATCH[3]}"
echo $str
It works even if the string doesn't have the space after the comma which seems optional.
Upvotes: 3
Reputation: 21502
Using SED:
string='internal func add(a: Int, b: Int) -> Int'
sed -e '
s/^.*func \+//
s/ *\->.*$//
s/:[^,)]\+/:/g
s/[, ]//g
' <<< "$string"
s/^.*func \+//
removes the front (^
) part before func
, func
, and spaces after func
;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.Upvotes: 2