How to replace an entire line in a text file by line number
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
How to search and replace text in a file?
fileinput
already supports inplace editing. It redirects stdout
to the file in this case:
#!/usr/bin/env python3
import fileinput
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_to_search, replacement_text), end='')
Replace String in Specific line in text file
Another approach with Linq
string[] file = File.ReadAllLines(@"c:\yourfile.txt");
file = file.Select((x, i) => i > 1 && i < 5 ? x.Replace("no", "number") : x).ToArray();
File.WriteAllLines(@"c:\yourfile.txt", file);
Replace line in text file using python
As you are reading from the file the file pointer moves as well and it can cause problems. What I would do is first read the file and prepare the "new file" that you want, and then write it into the file, as shown in the code below:
filetest = open ("testingfile.txt", "r")
lines = filetest.readlines()
filetest.close()
ID = input ("Enter ID: ")
list = ['Hello', 'Testing', 'File', 543210]
for i in range(len(lines)):
lines[i] = lines[i].rstrip()
if ID not in lines[i]:
continue
else:
templine = '\t'.join(map(str, list))
lines[i] = templine
with open("testingfile.txt", "w") as filetest:
for line in lines:
filetest.write(line + "\n")
I didn't change the logic of the code but be aware that if your file has, for example, a line with the number "56" and a line with the number "5", and you enter the ID "5", then the code will replace both of those lines.
Replace line in text file with a new line
First, open the file and save the actual content. Then, replace the string and write the full content back to file.
def remove_line(string)
# save the content of the file
file = File.read('test.txt')
# replace (globally) the search string with the new string
new_content = file.gsub(string, 'removed succesfully')
# open the file again and write the new content to it
File.open('test.txt', 'w') { |line| line.puts new_content }
end
Or, instead of replacing globally:
def remove_line(string)
file = File.read('test.txt')
new_content = file.split("\n")
new_content = new_content.map { |word| word == string ? 'removed succesfully' : word }.join("\n")
File.open('test.txt', 'w') { |line| line.puts new_content }
end
Python Replace content in specific line at txt file
Instead of that, what you can do is go with this code for editing the text file
with open(path_to_text_file,'r') as txt:
text=txt.readlines()
text[3]='phone number\n'
with open(path_to_text_file,'w') as txt:
txt.writelines(text)
replace string in specific line in text file in Python
try this out
f1 = open("last_file.txt", 'r+')
f2 = open("output_file.txt", 'w+')
keyString = '/string_to_search/'
oldString = "any other language"
newString = "python"
f2.write("".join([i.replace(oldString, newString) if keyString in i else i for i in f1.readlines()]))
f1.close()
f2.close()
For example this input file
random line
/string_to_search/ any other language
/string_to_search/ something?
writes the following to the output file:
random line
/string_to_search/ python
/string_to_search/ something?
Replace a line in a text file with any new line using python
Instead of using if statement, using regular expression will help you,
Since you are looking for a specific id followed by the word 'pending'
, a simple regex : "id=your_id=pending"
will work.
Then you can use re.sub
to replace the entire line by what you want. Here id=your_id=missing/found"
Note : this answer is probably not the best one, since you re-write most of the lines, but for small files, works perfectly.
import re
FILENAME = "textfile.txt"
def update_file(filename,id,word_to_add,lines_to_remove):
lines_to_remove = [s + "\n" for s in lines_to_remove]
#adding \n to all lines you want to remove
pattern =re.compile("^id="+str(id)+"=pending")
new_lines=[]
with open(FILENAME,'r+') as file:
for line in file:
if line not in lines_to_remove: # keeping only lines desired
new_lines.append(pattern.sub("id=1="+word_to_add,line))
with open(FILENAME,'w') as file:
file.writelines(new_lines)
return 0
update_file(FILENAME,1,"missing",["id=abc2=pending"])
#Output
#id=0=pending
#id=1=missing
Related Topics
How to Restart My Own Qt Application
Maximum Stack Size for C/C+ Program
Is There Any Use for Local Function Declarations
Assembly Adc (Add with Carry) to C++
Undefined Reference to Winmain (C++ Mingw)
Convert a Unicode String in C++ to Upper Case
Gcc - How to Create a Mapfile of the Object File
What Is the Meaning of Auto When Using C++ Trailing Return Type
Why Does My Program Hang When Opening a Mkfifo-Ed Pipe
How to Get a Color Palette from an Image Using Opencv
How to Use Boost Preprocessor to Generate Accessors
Set All Bytes of Int to (Unsigned Char)0, Guaranteed to Represent Zero
Is There an Automatic Noexcept Specifier
Include All Files in a Directory
Detach a Pointer from a Shared_Ptr
Differencebetween #Define and Const
How to Typedef a Function Pointer with the C++11 Using Syntax