Quantcast
Channel: User Dennis Williamson - Unix & Linux Stack Exchange
Viewing all articles
Browse latest Browse all 61

Answer by Dennis Williamson for Replace a string in a file preceeded by another string

$
0
0

This might be better done with awk in which you can use a state-machine style technique:

awk '/^reader_1 = newcamd\({/ { section_found = 1} /})/ { section_found = 0 } section_found && /port = 27020,$/ { sub(/27020,$/, "22443,") } { print }' file1 > file2 && mv file2 file1

Explanation:

Set a flag when the section start is found:

/^reader_1 = newcamd\({/ {
    section_found = 1
}

Clear the flag when the end of a section is found:

/})/ {
    section_found = 0
}

Substitute the new port number when in the right section and on the right line:

section_found && /port = 27020,$/ {
    sub(/27020,$/, "22443,")
}

Print all lines:

{
    print
}

Send output to file2 (a temporary file):

> file2

If everything was successful, rename file2 to file1:

&& mv file2 file1

You can make the regular expressions as loose or tight as you need.

This type of code is easier to read and maintain than sed or ed code, especially if you format it similarly to the way I have in my explanation.


Viewing all articles
Browse latest Browse all 61

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>