regex - Perl: Find line with matching string(str1) and only in those matched lines, replace one string(str2) with specific string(str3) -


i have 1 file a.txt contents follow:

a aa aaa b bb value = 11 xyz c cc ccc b bb value = 222 abc d dd ddd 

i have find string "bb". once matching line found have replace "value = xxx" "value = 77" here, xxx integer number of digit(11,222 in above case).

i have tried below perl command:

perl -n -e 'print; if (m/\bbb\b/) { s/value = (\d+)/value = 77/g; print; }' < a.txt 

it gives me output as:

a aa aaa b bb value = 11 xyz b bb value = 77 xyz c cc ccc b bb value = 22 abc b bb value = 77 abc d dd ddd 

here looking in-place replacement, instead of new line required changes. expecting output follow:

a aa aaa b bb value = 77 xyz c cc ccc b bb value = 77 abc d dd ddd 

can me here in updating command?

also 1 more quick question, can update above command in way can search string "bb" , matching lines remove string "value = xxx" matching line. xxx integer number of digit.

you print twice when have match. if don't want that, don't :)

perl -n -e 'if (m/\bbb\b/) { s/value = (\d+)/value = 77/g; } print' < a.txt 

cleaned up:

perl -pe's/value = \k\d+/77/g if /\bbb\b/' a.txt 

based on sample data, might able use

perl -pe's/\bbb\b.*value = \k\d+/77/' a.txt 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -