Nam Phan
Nam Phan

Reputation: 35

Bash script for replacing texts

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.

Upvotes: 1

Views: 51

Answers (1)

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10123

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

Upvotes: 2

Related Questions