Reputation: 4169
How can I use sed to duplicate part of a string?
hello foo(ignore this);
hello bar(or that);
hello func(or anything really);
with
hello foo(x) foo(y)
hello bar(x) bar(y)
hello func(x) func(y)
I know I can use & multiple times in the replace statement of sed but I have trouble having the matching pattern & be only what's between hello and (
Upvotes: 1
Views: 50
Reputation: 5665
I think you're on the right track with &
:
sed 's/(.*/(/; s/[^ ]*(/&x) &y)/' test.txt
s/(.*/(/
&
and repeat with x)
and y)
: s/[^ ]*(/&x) &y)/
[^ ]*
is capturing the string of non-space chars before the open parenUpvotes: 2
Reputation: 11247
Using sed
$ sed -E 's/([^ ]* ([^(]*)).*/\1(x) \2(y)/' input_file
hello foo(x) foo(y)
hello bar(x) bar(y)
hello func(x) func(y)
Upvotes: 2
Reputation: 4169
My solution is really not pretty: I remove what I don't want from each line until I only have my function names and then I re-add what I did. I am sure there must be a more elegant approach:
$ more test.txt
hello foo(ignore this);
hello bar(or that);
hello func(or anything really);
$ more test.txt | sed 's/hello //g' | sed 's/(.*$//g' | sed 's/.*/hello &(x) &(y)/g'
hello foo(x) foo(y)
hello bar(x) bar(y)
hello func(x) func(y)
Upvotes: 1