How to insert a string into a textfile
If it's a small file I think the easiest way would be to:
- Read the complete file.
- Insert the line.
- Write the new file.
That is the way Rails does it behind the scenes.
Or you can copy it line by line and then overwrite the original with mv
like this:
require 'fileutils'
tempfile=File.open("file.tmp", 'w')
f=File.new("file.txt")
f.each do |line|
tempfile<<line
if line.downcase=~/^line2/
tempfile << "Some nice little sentence\n"
end
end
f.close
tempfile.close
FileUtils.mv("file.tmp", "file.txt")
How do you insert a string at the beginning of a .txt file in C++
You can't insert data at the beginning of a file. You need to read the entire file into memory, insert data at the beginning, and write the entire thing back to disk. (I am assuming the file isn't too large).
Try this program.
#include <fstream>
#include <sstream>
int main()
{
std::stringstream stream;
stream << "First line\n"; // Add your line here!
{
std::ifstream file("filename.txt");
stream << file.rdbuf();
}
std::fstream new_file("filename.txt", std::ios::out);
new_file << stream.rdbuf();
return 0;
}
How to insert a constant string into a text file in every line after N characters in bash
with GNU sed
$ sed 's/ / xxx /3' file
Nov 30 23:09:39.029313 xxx sad asdadfahfgh
Nov 30 23:09:39.029338 xxx ads dsfgdsfgdf
Nov 30 23:09:46.246912 xxx hfg sdasdsa
Nov 30 23:09:46.246951 xxx jghjgh dfgdfgdf
Add new string in a text file with certain condition Python
Try this:
with open("prova.txt", "r+") as file:
lines = file.readlines()
# this will put the seek pointer to the end of file
file.seek(0,2)
if lines[len(lines) - 1] == '\n':
file.write("newRow")
else:
file.write("\nnewRow")
How to insert a string into a line in a file after a key word in bash
A pure sed solution:
sed -r "s:(THEKEYWORD):\1 $(sed ':a;N;$!ba;s/\n/ /g' test.txt) :g" insert.txt
Where;
test.txt
is the value to be inserted,$(sed ':a;N;$!ba;s/\n/ /g' test.txt)
removes any newlines from the file, so it can be inserted on the same lineinsert.txt
the text file whereTHEKEYWORD
exists
If you wish to replace the file, use the -i
option;
sed -i -r "s:(THEKEYWORD):\1 $(gsed ':a;N;$!ba;s/\n/ /g' test.txt) :g" insert.txt
As @KamilCuk pointed out, using paste -sd ' ' test.txt
could be used to remove the newlines, and insert the file;
sed -r "s:(THEKEYWORD):\1 $(paste -sd ' ' test.txt) :g" insert.txt
Terminal output + sed version
inserting contents of one text file into another in bash
If you want to edit a file directly, I always suggest ed
instead of the non-standard sed -i
(Where different implementions of sed
that do support it act differently, a common source of questions here):
printf "%s\n" "/TWO/r ext" w | ed -s base
will insert the contents of file ext after the first line containing TWO in base, and then write the new version of base back to disk.
If you must use sed
, the proper invocation will look very similar (No surprise since they're sibling commands):
sed -i '/TWO/r ext' base
(This will insert the ext file after every TWO in base, though, not just the first.)
The key in both is the r
command, which reads the contents of the given file and inserts it after a line with the matching address. Works a lot better than trying to read the file contents into a variable and including the text directly in the ed
/sed
commands.
If you want to insert the contents of a variable after the line, you can use
printf "%s\n" "/TWO/a" "$ext" . w | ed -s base
(As long as the variable doesn't have a line with just a period)
or with GNU sed
sed -i "/TWO/a ${ext//$'\n'/\\\n}" base
to append text after the addressed line.
How to insert characters at particular locations in text file
import io
# watch the `r` in header, footer & adding to raw_data lines, `r` is raw, it's meant to take strings as is
header= r'''\begin{longtable}{|c | c |}
\hline
$V_{out}$(in V) & $I_{out}$(in mA) \\ \hline'''
footer = r'''\caption{\\Output Characteristics for low input}
\label{tab:output@low}
\end{longtable}'''
with open('raw_data.txt', encoding='utf8') as raw_data, open('result.txt', 'w', encoding='utf8') as result:
result.write(header)
for line in raw_data.readlines():
datapoint1, datapoint2 = line.split()
result.write(datapoint1 + '& ' + datapoint2 + r'\\ \hline' + '\n')
result.write(footer)
Related Topics
What Does "Shadowing" Mean in Ruby
How to Generate Links with Trailing Slash in Rails 3
Net::Ssh Sudo Command Hangs After Entering Password
Assign/Replace Params Hash in Rails
How Does This Ruby Injection Magic Work
Elegant Chained 'Or's for Tests on Same Variable in Ruby
Rails 3.1 Absolute Url to an Image
How to Copy File Across Buckets Using Aws-S3 or Aws-Sdk Gem in Ruby on Rails
Devise Login with User or Admin Models and Basecamp Style Subdomains
Sort a Collection of Objects by Number (Highest First) Then by Letter (Alphabetical)
Windows/Ruby/Rails Install --- .Cannot Load Such File -- SQLite3/Sqlite3_Native Windows
Ruby Array to JSON and Rails JSON Rendering