1

I hava a file called a.txt. And it contains the following contents. It's unknow how many lines between each function.

function a(
line 1;
line 2;
line ...;
properties pro = "test";
)

function b(
line 1;
line 2;
line ...;
properties pro= "test";
)

function c(
properties pro= "test";
)

I want to edit

function b(
line 1;
line 2;
line ...;
properties pro= "test";
)

to the following

function b(
line 1;
line 2;
line ...;
properties pro= "replace";
)

Is it posssible to use one-line command like sed or awk?

1

1 Answer 1

2

Provided that your functions are delimited into paragraphs by one or more blank lines as shown, then you could use awk with an empty record separator. In particular, with GNU awk:

$ gawk '
    BEGIN{RS=""} 
    /^function b/ {sub(/properties pro= "test"/,"properties pro= \"replace\"")}
    {printf "%s%s", $0, RT}
' a.txt
function a(
line 1;
line 2;
line ...;
properties pro = "test";
)

function b(
line 1;
line 2;
line ...;
properties pro= "replace";
)

function c(
properties pro= "test";
)

You can use non-GNU awk as well, but you will need to set a fixed output record separator ORS since the RT separator is GNU-specific.

Perl provides a similar paragraph mode via the -00 option.

With sed, you could use a regular expression address range to limit the scope of the substitution ex.

$ sed '/^function b/,/^)$/s/properties pro= "test"/properties pro= "replace"/' a.txt
function a(
line 1;
line 2;
line ...;
properties pro = "test";
)

function b(
line 1;
line 2;
line ...;
properties pro= "replace";
)

function c(
properties pro= "test";
)

However bear in mind that things that may be syntactically neutral in your "language" (such as blank lines within a function) may break this approach - for this reason, regular expressions are often a poor choice for such tasks.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .