How to replace with pattern match using Perl

I have to replace a line, if it has a pattern for example
Suppose file.out contains:

<tr><td class="cB">Hello</td><td class="cB">1245</td><td class="cB">958</td><td class="cRB">1.34</td><td class="cRB">1.36</td></tr>
<tr><td class="cB">world</td><td class="cB">3256</td><td class="cB">364</td><td class="cB">1.23</td><td class="cB">2.58</td></tr>
<tr><td class="cB">Hello</td><td class="cB">1247</td><td class="cB">254</td><td class="cB">1.98</td><td class="cB">3.6</td></tr>

If the line has cRB, it has to replace cB with cRB for that line.

This can be done using sed as follows:

sed -e '/cRB/s/cB/cRB/g' file.out

But can I do this using inline replacement? I have tried 'i' but it says illegal option.

I have tried using perl but it does'nt seem to work:

find file.out -type f | xargs perl -pi -e '/cRB/s/cB/cRB/gi'

What system are you using?

SunOS

This should work:

find file.out -type f | xargs perl -pi -e '/cRB/&&s/cB/cRB/gi'
1 Like

Suppose I have a file like this:

Hello 1245 958 1.34 1.36

How can I wrap tags around them like below:

<tr><td class="cB">Hello</td><td class="cB">1245</td><td class="cB">958</td><td class="cRB">1.34</td><td class="cRB">1.36</td></tr>
awk -v OFS="</td><td class="cB">" '{ $1=$1; print "<tr><td class="cB">", $0, "</td></tr>" }' input > output
1 Like
perl -ple 's/[^ ]+/<td class="cB">$&<\/td>/g;s/> </></g;s/.*/<tr>$&<\/tr>/' file

Thanks, But I am getting the output as follows

<tr><td class=></td><td class=cB>Hello</td><td class=cB>1245</td><td class=cB>958</td><td class=cB>1.34</td><td class=cB>1.36</td><td class=cB></td></tr>

Did you try code I posted earlier?

perl -ple 's/[^ ]+/<td class="cB">$&<\/td>/g;s/> </></g;s/.*/<tr>$&<\/tr>/' file
1 Like