I need to change something like

<1> to _1
<21> to _21

Is there a way I can automate this using sed, or awk or vi ?

Note: The number inside the angular brackets varies.

  • Yes that is possible, it is also possible to do that just with the shell. Is asking whether it is possible really helpful? You could have tried and found a solution in max 5 minutes of searching+reading. Then you would have known that it is possible and how to do it? – Anthon Sep 2 '17 at 6:25

With sed:

sed 's/<\([0-9]*\)>/_\1/g'

Running this on the example in the question produces

_1 to _1
_21 to _21

The pattern <\([0-9]*\)> matches any number of digits inside <...>. The replacement text replaces this <...> bit of input with the digits (if there are any) prefixed by _.

In Vi:


This is equivalent to the sed solution, for obvious historical reasons.

If you have the string <21> in a shell variable var in Bash:

printf '%s\n' "_${var//[<>]/}"

This will print _21 using the variable substitution ${parameter//pattern/string}.

With tr. Note: This gives the appearance of working on a very limited set of input. It blindly replaces < with _ and deletes >, with no regard for where they occur:

tr '<' '_' <file.in | tr -d '>'

This is more of a joke solution than anything serious, but will work if the only < and > that occurs in the input are the ones with digits in-between.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.