I have a situation where I want a bash script to replace an entire line in a file. The line number is always the same, so that can be a hard-coded variable.
I'm not trying to replace some sub-string in that line, I just want to replace that line entirely with a new line.
Are there any bash methods for doing this (or something simple that can be thrown into a .sh script).
The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.
Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.
Replace all instances of a text in a particular line of a file using 'g' option. 'g' option is used in `sed` command to replace all occurrences of matching pattern.
Not the greatest, but this should work:
sed -i 'Ns/.*/replacement-line/' file.txt
where N
should be replaced by your target line number. This replaces the line in the original file. To save the changed text in a different file, drop the -i
option:
sed 'Ns/.*/replacement-line/' file.txt > new_file.txt
I actually used this script to replace a line of code in the cron file on our company's UNIX servers awhile back. We executed it as normal shell script and had no problems:
#Create temporary file with new line in place
cat /dir/file | sed -e "s/the_original_line/the_new_line/" > /dir/temp_file
#Copy the new file over the original file
mv /dir/temp_file /dir/file
This doesn't go by line number, but you can easily switch to a line number based system by putting the line number before the s/
and placing a wildcard in place of the_original_line
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With