0

I have problem with formating text in BASH using sed. This is the input file:

recfun.o -> timeout.o (set_timeout) recursive.o -> timeout.o (timeout) print_recursive.o -> recursive.o (ackermann) rec-nam.o -> timeout+.o (timeout) 

and this shloud be the output:

recfunDo -> timeoutDo [label="set_timeout"]; recursiveDo -> timeoutDo [label="timeout"]; print_recursiveDo -> recursiveDo [label="ackermann"]; rec_namDo -> timeoutPDo [label="timeout"]; 

Which means this:

substitute: "-" for "_", then "." for "D", then "+" for "P", but do not substitute " ->" for " _>"

I have used sed like this:

sed -e 's/./D/' file | sed -e 's/+/P/' | sed -e 's/-/_/' 

But it returns the same output with just D substituted for first letter in each line.

Thank you for help!

3 Answers 3

3

. matches any character in the pattern, hence it always changed the first letter. Escaping it as \. helps. The full command:

sed 's/\./D/g; s/+/P/g; s/-\([^>]\)/_\1/; s/(/[label="/; s/)/"];/' myfile recfunDo -> timeoutDo [label="set_timeout"]; recursiveDo -> timeoutDo [label="timeout"]; print_recursiveDo -> recursiveDo [label="ackermann"]; rec_namDo -> timeoutPDo [label="timeout"]; 

As Trenin notes in the comment, multiple commands separated with ; are grouped in one sed script here. The part s/-\([^>]\)/_\1/ uses a numbered group denoted with \(...\) (and refers to it as \1 in the replacement part) and a character class inside the group: [^>]. This matches any character except >.

Sign up to request clarification or add additional context in comments.

1 Comment

You might want to add some explanation. For example, OP might not know that you can chain multiple commands with the ;. Also, to get around replacing ->, you've matched - followed by anything other than >. Good answer though!
0

You need to escape the .

sed -e 's/\./D/g' file 

4 Comments

Also use /g to do multiple replacements in the same line.
@fedorqui missed the global, fixed
oh, I see, sorry, I am new to bash
@user3021851 Technically, this is not a bash feature, it's just sed regex (see e.g. here).
0

Perl's regular expressions are handy here:

perl -pe 'tr/.+/DP/; s/-(?!>)/_/g; s/\((.+?)\)$/[label="$1"];/' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.