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

BashTextReplaceSed

Bash Problem Overview


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

Bash Solutions


Solution 1 - Bash

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

Solution 2 - Bash

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.

Solution 3 - Bash

Let's suppose you want to replace line 4 with the text "different". You can use AWK like so:

awk '{ if (NR == 4) print "different"; else print $0}' input_file.txt > output_file.txt

AWK considers the input to be "records" divided into "fields". By default, one line is one record. NR is the number of records seen. $0 represents the current complete record (while $1 is the first field from the record and so on; by default the fields are words from the line).

So, if the current line number is 4, print the string "different" but otherwise print the line unchanged.

In AWK, program code enclosed in { } runs once on each input record.

You need to quote the AWK program in single-quotes to keep the shell from trying to interpret things like the $0.

EDIT: A shorter and more elegant AWK program from @chepner in the comments below:

awk 'NR==4 {$0="different"} { print }' input_file.txt

Only for record (i.e. line) number 4, replace the whole record with the string "different". Then for every input record, print the record.

Clearly my AWK skills are rusty! Thank you, @chepner.

EDIT: and see also an even shorter version from @Dennis Williamson:

awk 'NR==4 {$0="different"} 1' input_file.txt

How this works is explained in the comments: the 1 always evaluates true, so the associated code block always runs. But there is no associated code block, which means AWK does its default action of just printing the whole line. AWK is designed to allow terse programs like this.

Solution 4 - Bash

Given this test file (test.txt)

Lorem ipsum dolor sit amet,
consectetur adipiscing elit. 
Duis eu diam non tortor laoreet 
bibendum vitae et tellus.

the following command will replace the first line to "newline text"

$ sed '1 c\
> newline text' test.txt

Result:

newline text
consectetur adipiscing elit. 
Duis eu diam non tortor laoreet 
bibendum vitae et tellus.

more information can be found here

http://www.thegeekstuff.com/2009/11/unix-sed-tutorial-append-insert-replace-and-count-file-lines/

Solution 5 - Bash

in bash, replace N,M by the line numbers and xxx yyy by what you want

i=1
while read line;do
  if((i==N));then
    echo 'xxx'
  elif((i==M));then
    echo 'yyy'
  else
    echo "$line"
  fi
  ((i++))
done  < orig-file > new-file

EDIT

In fact in this solution there are some problems, with characters "\0" "\t" and ""

"\t", can be solve by putting IFS= before read: "", at end of line with -r

IFS= read -r line

but for "\0", the variable is truncated, there is no a solution in pure bash : https://stackoverflow.com/questions/6570531/assign-string-containing-null-character-0-to-a-variable-in-bash But in normal text file there is no nul character \0

perl would be a better choice

perl -ne 'if($.==N){print"xxx\n"}elsif($.==M){print"yyy\n"}else{print}' < orig-file > new-file

Solution 6 - Bash

# Replace the line of the given line number with the given replacement in the given file.
function replace-line-in-file() {
    local file="$1"
    local line_num="$2"
    local replacement="$3"
    
    # Escape backslash, forward slash and ampersand for use as a sed replacement.
    replacement_escaped=$( echo "$replacement" | sed -e 's/[\/&]/\\&/g' )
    
    sed -i "${line_num}s/.*/$replacement_escaped/" "$file"
}

Solution 7 - Bash

Excellent answer from Chepner. It is working for me in bash Shell.

 # To update/replace the new line string value with the exiting line of the file
 MyFile=/tmp/ps_checkdb.flag

 `sed -i "${index}s/.*/${newLine}/" $MyFile`

here
index - Line no
newLine - new line string which we want to replace.


Similarly below code is used to read a particular line in the file. This won't affect the actual file.

LineString=`sed "$index!d" $MyFile` 

here
!d - will delete the lines other than line no $index So we will get the output as line string of no $index in the file.

Solution 8 - Bash

On mac I used

sed -i '' -e 's/text-on-line-to-be-changed.*/text-to-replace-the=whole-line/' file-name

Solution 9 - Bash

Replace line with sed c\

Reference

sed c\ won't actually change the file, so you need to send its output to a temp file then cat the temp file into the original. Matching pattern not necessary because we can specify the line. Example: sed '1 c\' => will replace the text in line 1.

When writing the command, anything after the c\ part goes in a new line and should contain the new line text.


Finally, the example to "replace" line 1 in a file named original_file.txt with the text 'foo'. Note that we are taking the sed output and saving in a temp file, then outputing the temp file back into the original:

# file contents
$ cat original_file.txt
bar

# the replace command
$ sed '1 c\
  foo' original_file.txt > temp_file.txt
 
# output contents of temp_file and overwrite original
$ cat temp_file.txt > original_file.txt

# delete the temp file
$ rm -rf temp_file.txt

Solution 10 - Bash

If you want to use parameters for lineNumber and replacingLine then awk not working easily (for me). I run after 1 hour try you can see below :)

lineNumber=$(grep --line-number "u want to replace line any keyword" values.txt  | cut -f1 -d:)
replacedLine="replacing new Line "
# for sed prepare => if your replacedLine have '/' character (URL or something) u must use command bellow. 
replacedLine=${replacedLine//\//\\\/}

sed -i $lineNumber's/.*/'"$replacedLine"'/'  values.txt

Solution 11 - Bash

You can even pass parameters to the sed command:

test.sh

#!/bin/bash
echo "-> start"
for i in $(seq 5); do
  # passing parameters to sed
  j=$(($i+3))
  sed -i "${j}s/.*/replaced by '$i'!/" output.dat
done
echo "-> finished"
exit 

orignial output.dat:

a
b
c
d
e
f
g
h
i
j

Executing ./test.sh gives the new output.dat

a
b
c
replaced by '1'!
replaced by '2'!
replaced by '3'!
replaced by '4'!
replaced by '5'!
i
j

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser788171View Question on Stackoverflow
Solution 1 - BashchepnerView Answer on Stackoverflow
Solution 2 - BashKyleView Answer on Stackoverflow
Solution 3 - BashstevehaView Answer on Stackoverflow
Solution 4 - BashEric RobinsonView Answer on Stackoverflow
Solution 5 - BashNahuel FouilleulView Answer on Stackoverflow
Solution 6 - BashDaniel BighamView Answer on Stackoverflow
Solution 7 - BashKanagavelu SugumarView Answer on Stackoverflow
Solution 8 - BashnakeerView Answer on Stackoverflow
Solution 9 - BashEsteban gsView Answer on Stackoverflow
Solution 10 - BashTalha DilberView Answer on Stackoverflow
Solution 11 - BashAndreHView Answer on Stackoverflow