LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Remove trailing characters while adding leading characters (https://www.linuxquestions.org/questions/programming-9/remove-trailing-characters-while-adding-leading-characters-4175735650/)

danielbmartin 04-06-2024 12:53 PM

To further generalize...

Suppose the alchemist want to change two base metals to one precious metal.

With this InFile ...
Code:

m1_IRON some other text m2_IRON
p2_LEAD yet more text p2_IRON extra text
change is good hello_LEAD

... this code ...
Code:

BaseMetal1='IRON'
BaseMetal2='LEAD'
PreciousMetal='GOLD'
sed -r 's/([[:alnum:]]+)_('$BaseMetal1'|'$BaseMetal2')/'$PreciousMetal'_\1/g' <$InFile >$OutFile

... produces this OutFile ...
Code:

GOLD_m1 some other text GOLD_m2
GOLD_p2 yet more text GOLD_p2 extra text
change is good GOLD_hello

Daniel B. Martin

.


All times are GMT -5. The time now is 12:03 PM.