Kailash Sundar
Kailash Sundar

Reputation: 1

how to replace multiple lines in a file after a specific character with null in unix

For example, if my file contains

{z:
abdc
cabdfd
cabdfd
casfdbf
cdff
-}$

Once find the string value {z: the multiple lines after that upto -} must be replaced by null character and it should follow the same procedure globally throughout the file.

This must be done in Unix I tried using sed command to search for multiple lines but unable to succeed with it though.

Upvotes: 0

Views: 77

Answers (2)

JJoao
JJoao

Reputation: 5347

If I understand correctly try the following perl solution

#!/usr/bin/perl

undef $/;     ## register separator is undefined
my $t=<>;     ## slurp all input to $t

$t =~ s/\{z:.*?\n-\}/\0/gs;   ## substitute patt by \0
print $t;

Usage: perl thisscript input

If you need a more complex transformation inside the pattern I would suggest:

#!/usr/bin/perl

undef $/;     ## register separator is undefined
my $t=<>;     ## slurp all input to $t

$t =~ s/(\{z:.*?\n-\})/norm($1)/gse;   ## substitute patt by its norm
print $t;

sub norm{ my $s = shift;
    ## transform $s
    return $s
}

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26667

You can specify an address range in sed so that the action is performed for lines within the range

To delete the lines within the two pattern

$ cat input
{z:
abdc
cabdfd
cabdfd
casfdbf
cdff
-}$
hello
world

$ sed '/^{z:$/, /$-}\$$/d' input
hello
world
  • /^{z:$/, /^-}\$$/ specifies the start and end of the range.

To replace with null string

You can use the substitute command as

$ sed '/^{z:/, /-}\$$/s/.*//' input







hello
world

Upvotes: 1

Related Questions