maddyfrank
maddyfrank

Reputation: 63

How to match string between two strings in a file and manipulate the matched string with sed?

I am trying to manipulate a file using sed which contains text and the program should match the info between the two strings and add a new space before each line in the file between the matched strings .

part of file looks like this :

Change: ****
Client: ****
User:  manny

Status: pending

Description:
this is example text
this is example text
this is example text

Files:
//network paths
//network paths

i am trying to manipulate this file to match the text between Description and Files and introduce a white space before each line in matched text .

end result should look like this :

Change: ****
Client: ****
User:  manny

Status: pending

Description:
 this is example text
 this is example text
 this is example text

Files:
//network paths
//network paths

I have tried this command :

sed -i -e 's/Description:(^.*)Files:/ / ' filename.txt

its not working as i expected to . now when i tried just to add white space before each line with sed -i -e 's/^/ /' filename.txt

this works fine while introducing whitespace before each line in the file .

Someone suggest point me out where i am going wrong and maybe how to achieve the expected solution.

Upvotes: 0

Views: 132

Answers (3)

oguz ismail
oguz ismail

Reputation: 50750

Between two patterns add a space at the beginning of each line, exclusively.

sed '/^Description:/,/^$/{//!s/^/ /}' file

Concerning //, it's described in POSIX sed specification as follows:

If an RE is empty (that is, no pattern is specified) sed shall behave as if the last RE used in the last command applied (either as an address or as part of a substitute command) was specified.

Given your sample its output looks like:

Change: ****
Client: ****
User:  manny

Status: pending

Description:
 this is example text
 this is example text
 this is example text

Files:
//network paths
//network paths

In order to cover both cases that there may or may not be a blank line before Files:, this can be used:

sed '/^Description:/,/^Files:/{//!s/^./ &/}' file

Upvotes: 1

Walter A
Walter A

Reputation: 20002

When you are not sure that you can use a blank line as the last line, you can do

sed '/Description:/,/Files:/ s/^/ /; s/ \(Description\|Files\):/\1:/' file

or

d="Description"
f="Files"
sed "/$d:/,/$f:/ s/^/ /; s/ \($d\|$f\):/\1:/" file

Upvotes: 0

Cyrus
Cyrus

Reputation: 88601

Not very elegant, but it works.

sed '/^Description:/,/^$/{ /^Description\|^$/b; s/.*/ &/}' file

Output:

Change: ****
Client: ****
User:  manny

Status: pending

Description:
 this is example text
 this is example text
 this is example text

Files:
//network paths
//network paths

Upvotes: 2

Related Questions