Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace an entire line in a text file by line number

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).

like image 584
user788171 Avatar asked Sep 26 '22 13:09

user788171


People also ask

How do you replace a line in a text file in bash?

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.

How do I sed a particular line?

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.

How do you replace a specific line in Unix?

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.


2 Answers

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
like image 290
chepner Avatar answered Oct 17 '22 06:10

chepner


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.

like image 47
Kyle Avatar answered Oct 17 '22 05:10

Kyle