User Tools

Site Tools


bash:files:find_replace_a_string_within_a_file

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
bash:files:find_replace_a_string_within_a_file [2021/02/10 16:06] peterbash:files:find_replace_a_string_within_a_file [2021/02/10 16:14] (current) – [Put the output of file f1 into the pattern space of file f2] peter
Line 1: Line 1:
 ====== BASH - Files - Find & Replace a String within a File ====== ====== BASH - Files - Find & Replace a String within a File ======
 +
 +See:  [[BASH:Strings:Find & Replace|Find & Replace]].
 +
 +----
  
 ===== Changing contents within a file ===== ===== Changing contents within a file =====
Line 22: Line 26:
 <code bash> <code bash>
 echo "${contents/$old/$new}" > infile.tmp && mv infile.tmp infile.txt echo "${contents/$old/$new}" > infile.tmp && mv infile.tmp infile.txt
 +</code>
 +
 +----
 +
 +===== Put the output of file1 into the pattern space of file2 =====
 +
 +<file text file1>
 +aaaaaaaaaaaaaaaaaa //these line go in file2
 +aaaaaaaaaaaaaaaaaa
 +aaaaaaaaaaaaaaaaaa
 +</file>
 +
 +<file text file2>
 +Pattern_start
 +__________ //these are the line to be replaced
 +__________
 +Pattern_end
 +</file>
 +
 +<code bash>
 +sed -n '/Pattern_start/,/Pattern_end/{/^Pattern/! d;}" file2 | sed "/Pattern_start/r file1"
 +</code>
 +
 +<WRAP info>
 +**NOTE:**  
 +
 +  * **<nowiki>/^Pattern/</nowiki>**:  Used this to avoid deleting the **Pattern_start** and **Pattern_end** lines.
 +</WRAP>
 +
 +----
 +
 +If the lines between Pattern_start and Pattern_end contain only hyphens then you can use this:
 +
 +<code bash>
 +sed -n '/Pattern_start/,/Pattern_end/{/^---*/d;}" file2 | sed "/Pattern_start/r file1"
 </code> </code>
  
bash/files/find_replace_a_string_within_a_file.1612973179.txt.gz · Last modified: 2021/02/10 16:06 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki