-->

How to replace multi-line text in bash programming

2020-08-01 06:39发布

问题:

I want to replace the following text

text := a \
        b \
        c

with the following one:

text := d \
        e \
        f

in bash file.

I have tried different versions of 'sed', but none of them worked e.g.:

old_path='text := a \\\n\t\tb \\\n\t\tc'
new_path='text := d \\\n\t\te \\\n\t\tf'
sed -i -e "s%old_path%new_path%g" text.txt

回答1:

if you do not mind using Perl try:

~ ❱ perl -pe 's/ ((?=[a-z]).)/" ".chr(ord($1)+3)/eg' file
text := d \
        e \
        f 
~ ❱ 

the ASCII code for your character is: 100, 101 and 102
Thus if you add 3 to them they from a b c become d e f



回答2:

try with simple sed.

sed 's/a \\/d \\/;s/b \\/e \\/;s/c/f/'   Input_file

Explanation: Simply I am using substitute option of sed by using s/text_which_needs_to_be_replaced/new_text. BY separating them with semi colon will make sure we could perform multiple substitutions. substitutions are made by as per your need. Kindly do let me know if you have any queries on same.



回答3:

This might work for you (GNU sed):

sed '/^text := a \\/,/^\tc$/c\test := d \\\n\te \\\n\tf' file

Change the text in the range '/^text := a \\/,/^\tc$/ to the required values.



标签: bash sed