Reputation: 553
I'm trying to search the substring using 'sed'.
For example extract the string word before '(' character and print it.
Below expression only works if there is no whitespace between word and '(' character.
$ echo "void fun()" | sed 's/.* \(.*\)(.*/\1/'
fun
$ echo "void fun ()" | sed 's/.* \(.*\)(.*/\1/'
so, what is the right expression to search string word which is followed by space|non-space '(' character.
Upvotes: 0
Views: 99
Reputation: 241988
Sed is for editing, grep is for searching.
$ echo $'void fun()\nvoid fun ()' | grep -o '\S\S*\s*()'
fun()
fun ()
\S
means non whitespace*
means repeated 0 or more times\s
means whitespace-o
only prints the matching partUpvotes: 1
Reputation: 23677
*
is greedy, will try to match as much as possible. So I'd suggest to avoid .*
and instead use something that won't match more than necessary. [^ ]*
will match only non-space character
$ echo "void fun()" | sed 's/^[^ ]* \([^ ]*\) *(.*/\1/'
fun
$ echo "void fun ()" | sed 's/^[^ ]* \([^ ]*\) *(.*/\1/'
fun
IMO, this is simpler to do using awk
$ echo "void fun()" | awk -F'[ (]' '{print $2}'
fun
$ echo "void fun ()" | awk -F'[ (]' '{print $2}'
fun
-F'[ (]'
use space or (
as field separatorprint $2
print second fieldUpvotes: 1