Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to replace part of a file's data, with data from another file.

Suppose file1 has data as is written below and file2 has some data I want to store and replace file1 data from file2 from starting pattern: // +++ CUSTOMIZATION SETTINGS START +++ and the end pattern: // +++ CUSTOMIZATION SETTINGS END +++.

In file1:

ANJALI
NISHA

// +++ CUSTOMIZATION SETTINGS START +++ 

WE WILL BE ON LEAVE FOR TODAY 

// +++ CUSTOMIZATION SETTINGS END +++ 

PREETI
MONA

In file2:

MANISH
MADHVI

// +++ CUSTOMIZATION SETTINGS START +++ 

WELCOME  ALL 

// +++ CUSTOMIZATION SETTINGS END +++ 

NISHA
TUSHAR

In file3 as output:

ANJALI
NISHA

// +++ CUSTOMIZATION SETTINGS START +++ 

WELCOME  ALL 

// +++ CUSTOMIZATION SETTINGS END +++ 

PREETI
MONA
share|improve this question

1 Answer 1

up vote 5 down vote accepted
$ awk '/SETTINGS START/,/SETTINGS END/ {if (FNR==NR) {a=a"\n"$0}} FNR==NR{next}   /SETTINGS START/{print substr(a,2)} /SETTINGS START/,/CUSTOMIZATION SETTINGS END/{next}  1' file2 file1
ANJALI NISHA

// +++ CUSTOMIZATION SETTINGS START +++

WELCOME ALL

// +++ CUSTOMIZATION SETTINGS END +++

PREETI MONA

Explanation

awk implicitly loops through files line by line. In this case, we have it loop through file2 first, then file1.

  • /SETTINGS START/,/SETTINGS END/ {if (FNR==NR) {a=a"\n"$0}}

    The settings section from file2 is captured in the variable a.

  • FNR==NR{next}

    If we are still reading file2, skip the rest of the commands and jump to the next line of input.

  • /SETTINGS START/{print substr(a,2)}

    If we get here, we are processing file1. When we see the start of the settings section, print the string that we have saved in the variable a.

  • /SETTINGS START/,/CUSTOMIZATION SETTINGS END/{next}

    If we are in the settings section of file1, skip the rest of the commands and go to the next input line.

  • 1

    1 is awk's cryptic shorthand for print the current line. We only get to this statement if we are in file1 but not in the settings section.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.