Home > database >  Bash script for replacing texts
Bash script for replacing texts

Time:12-15

I have a file.txt file as in the following example:

Part 1

Some texts #abc d#ae}gd1 l2#4.

Part 2

Some texts again #efd de#gm}dg 12#a.

I want "#" is replaced by "hi" in the whole file, however in part 2 I also want to put the part from # up to the first character that's not in 0-9A-Za-z inside "check{ }".

So this is the output:

Part 1

Some texts hiabc dhiae}gd1 l2hi4.

Part 2

Some texts again check{hiefd} decheck{higm}}dg 12check{hia}.

I only knew how to replace # by "hi" in the whole:

awk '{gsub(/#/,"hi")} 1' file.txt > output.txt ;

It's really difficult for me to find a way to handle the requirement in part 2.

Thank for any help.

I wanted to find a solution for this.

CodePudding user response:

This sed command should do the trick:

sed '/Part 1/,/Part 2/s/#/hi/g
     /Part 2/,$s/#\([0-9A-Za-z]*\)/check{hi\1}/g
' file
  • Related