LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   replace only the first line of a file without temporary files (https://www.linuxquestions.org/questions/linux-software-2/replace-only-the-first-line-of-a-file-without-temporary-files-720709/)

DeepSeaNautilus 04-21-2009 12:20 PM

replace only the first line of a file without temporary files
 
hello I have a file in which I want to replace the first line with the context of another file. I have done this with temporary files, with I want to know if there is an easier and more efficient way to do this with sed, awk or other stream editor.

I have a main file whose content is:
header

text...
...
text...

I have a file that has the text I want to insert in the fist line.
The output I want is

newHeader

text...
...
text...

How can I do this without using temporary files? Thanks

druuna 04-21-2009 01:33 PM

Hi,

As always there are probably others ways of doing this, but this should work:

- A sed solution -

Code:

#!/bin/bash
sed -i '/header/ {
  r newheader
  d
}' $1

Sed searches for header (the /header/ part) and if found replace it with the content of the file called newheader (the r newheader and d part). The -i saves changes immediately.


Files used and testrun:

Quote:

cat mainfile

a one line header

Text text .......
Text text .......


Text text .......

Text text .......


cat newheader
This is

--- The New Header ---

that's all folks


./replaceheader mainfile

This is

--- The New Header ---

that's all folks

Text text .......
Text text .......


Text text .......

Text text .......


All times are GMT -5. The time now is 07:23 AM.