Home > Blockchain >  prevent sed replacements from overwriting each other
prevent sed replacements from overwriting each other

Time:02-04

I want to replace A with T and T with A

sed -e 's/T/A/g;s/A/T/g

as an example above line changes A:T to T:T

I am hoping to get T:A.

How do I do this?

CodePudding user response:

If you want to change single characters, it is simply:

sed 'y/TA/AT/'

If you want to change longer (non-overlapping) strings, you need a temporary value that you know is never used. Conveniently, newline can never appear. So:

sed '
     s/T/\n/g
     s/A/T/g
     s/\n/A/g
'

CodePudding user response:

I'm not a SED expert - so not sure if that can be done as a single command. Just wondering if you've thought about doing that swap like you would in a programming language that would need a temporary variable to do the switch?

Maybe like change the A to a value you know you don't have in the string like Y for example. Then change the T to A and then change Y to T. Would something like that work?

Edit: I did a quick search just out of curiosity. Found this: https://unix.stackexchange.com/questions/528994/swapping-words-with-sed

In case that helps, but with regex stuff, the result is highly dependent on how structured and unique your inputs are. Not sure how to just swap two arbitrary sub-strings or characters throughout an entire string if there's no particular structure that tells you when you're about to get that sub-string or character like the answer above looking for the parenthesis.

CodePudding user response:

Use this Perl one-liner for case-sensitive replacement:

echo 'TATAtata' | perl -pe 'tr{AT}{TA}'
ATATtata

Or this one-liner for case-insensitive replacement:

echo 'TATAtata' | perl -pe 'tr{ATat}{TAta}'
ATATatat

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-p : Loop over the input one line at a time, assigning it to $_ by default. Add print $_ after each loop iteration.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc tr
perldoc tr/SEARCHLIST/REPLACEMENTLIST/cdsr

  • Related