bash:files:find_replace_a_string_within_a_file
This is an old revision of the document!
Table of Contents
BASH - Files - Find & Replace a String within a File
See: Find & Replace.
Changing contents within a file
contents=$(< infile.txt) $ echo "${contents/$old/$new}"
NOTE: This reads the file into a Bash variable and uses parameter expansion.
- infile.txt: The input file here is named infile.txt.
- $old: The string to replace.
- $new: The replacement string.
To change the file in-place:
echo "${contents/$old/$new}" > infile.tmp && mv infile.tmp infile.txt
Put the output of file f1 into the pattern space of file f2
- f1
wjwjwjwjwjwjwj //these line go in file f2 jwjwjwjwjwjjwjw wjwjwjwjjwjwjwj
- f2
Pattern_start __________ //these are the line to be replaced __________ Pattern_end
sed -n '/Pattern_start/,/Pattern_end/{/^Pattern/! d;}" file2 | sed "/Pattern_start/r f1"
NOTE:
- /^Pattern/: Used this to avoid deleting the Pattern_start and Pattern_end lines.
If the lines between Pattern_start and Pattern_end contain only hyphens then you can use this
bash/files/find_replace_a_string_within_a_file.1612973520.txt.gz · Last modified: 2021/02/10 16:12 by peter