I am trying to modify a text file I am using PHP or also I can use the C# the file that I am working on a text file consists of strings for example
TM_len= --------------------------------------------
EMM_len --------------------------------------------
T_len=45 CTGCCTGAGCTCGTCCCCTGGATGTCCGGGTCTCCCCAGGCGG
NM_=2493 ----------------ATATAAAAAGATCTGTCTGGGGCCGAA
and I want to delete those four lines from the file if I found that one line consists of only "-" no characters in it and of course save to the file.
Maybe something like this? I wrote it in a easy to understand and "not-shortened" way:
$newfiledata = "";
$signature = " ";
$handle = fopen("inputfile.txt", "r"); // open file
if ($handle) {
while (($line = fgets($handle)) !== false) { // read line by line
$pos = strpos($line, $signature); // locate spaces in line text
if ($pos) {
$lastpart = trim(substr($line, $pos)); // get second part of text
$newstring = trim(str_replace('-', '', $line)); // remove all dashes
if (len($newstring) > 0) $newfiledata .= $line."\r\n"; // if still there is characters, append it to our variable
}
}
fclose($handle);
}
// write new file
file_put_contents("newfile.txt", $newfiledata);
thanks for your response but there nothing happened on the file please check the link of the file and another link of the desired output for the file.download the file and required output file
Related
How do I completely remove a line in Rust? Not just replace it with an empty line.
In Rust, when you delete a line from a file with the following code as an example:
let mut file: File = File::open("file.txt").unwrap();
let mut buf = String::from("");
file.read_to_string(&mut buf).unwrap(); //Read the file to a buffer
let reader = BufReader::new(&file);
for (index, line) in reader.lines().enumerate() { //Loop through all the lines in the file
if line.as_ref().unwrap().contains("some text") { //If the line contains "some text", execute the block
buf = buf.replace(line.as_ref().unwrap(), ""); //Replace "some text" with nothing
}
}
file.write_all(buf.as_bytes()).unwrap(); //Write the buffer back to the file
file.txt:
random text
random text
random text
some text
random text
random text
When you run the code, file.txt turns into this:
random text
random text
random text
random text
random text
Rather than just
random text
random text
random text
random text
random text
Is there any way to completely remove the line rather than just leaving it blank? Like some sort of special character?
This part is bad-news: buf = buf.replace(line.as_ref().unwrap(), "");
This is doing a search through your entire buffer to find the line contents (without '\n') and replace it with "". To make it behave as you expect you need to add back in the newline. You can just about do this by buf.replace(line.as_ref().unwrap() + "\n", "") The problem is that lines() treats more than "\n" as a newline, it also splits on "\r\n". If you know you're always using "\n" or "\r\n" as newlines you can work around this - if not you'll need something tricker than lines().
However, there is a trickier issue. For larger files, this may end up scanning through the string and resizing it many times, giving an O(N^2) style behaviour rather than the expected O(N). Also, the entire file needs to be read into memory, which can be bad for very large files.
The simplest solution to the O(N^2) and memory issues is to do your processing line-by-line, and
then move your new file into place. It would look something like this.
//Scope to ensure that the files are closed
{
let mut file: File = File::open("file.txt").unwrap();
let mut out_file: File = File::open("file.txt.temp").unwrap();
let reader = BufReader::new(&file);
let writer = BufWriter::new(&out_file);
for (index, line) in reader.lines().enumerate() {
let line = line.as_ref().unwrap();
if !line.contains("some text") {
writeln!(writer, "{}", line);
}
}
}
fs::rename("file.txt.temp", "file.txt").unwrap();
This still does not handle cross-platform newlines correctly, for that you'd need a smarter lines iterator.
Hmm could try removing the new line char in the previous line
I tried to get a script to create a text file that could write/add the images name, but the function
FileID = CreateFileForWriting(filename) does not work, it shows that was used by other process
I did not get this, is this function not right format or something is wrong, thx
Number Totaln
totaln=countdocumentwindowsoftype(5)
String filename, text
Number fileID
if (!SaveasDialog( "save text file as",getapplicationdirectory(2,0) + "Imagename.txt", filename))exit(0)
fileID = CreateFileForWriting(filename)
number i
for(i = 0; i <totaln; i++)
{
image imgSRC
imgSRC := GetFrontImage()
string imgname=getname(imgSRC)
WriteFile(fileID,"imgname")
Result("imgname")
}
Your code is nearly fine, but if you use the low-level API for file I/O you need to ensure that you close files you've opened or created.
Your script doesn't. Therefore, it runs fine exactly 1 time but will fail on re-run (when the file is still considered open.)
To fix it, you need to have closefile(fileID) at the end.
( BTW, if you script exits or throws after opening a file but before closing it, you have the same problem. )
However, I would strongly recommend not using the low-level API but the file streaming object instead. It also provides an automated file-closing mechanism so that you don't run into this issue.
Doing what you do in your script would be written as:
void writeCurrentImageNamesToText()
{
number nDoc = CountImageDocuments()
string filename
if (!SaveasDialog( "save text file as",getapplicationdirectory(2,0) + "Imagename.txt", filename)) return
number fileID = CreateFileForWriting(filename)
object fStream = NewStreamFromFileReference(fileID,1) // 1 for auto-close file when out of scope
for( number i = 0; i <nDoc; i++ ){
string name = GetImageDocument(i).ImageDocumentGetName()
fStream.StreamWriteAsText( 0, name + "\n" ) // 0 = use system encoding for text
}
}
writeCurrentImageNamesToText()
I have several files with datas in it.
For example: file01.csv with x lignes in it, file02.csv with y lines in it.
I would like to treat and merge them with mapreduce in order to get a file with the x lines beginning with file01 then line content, and y files beginning with file02 then line content.
I have two issues here:
I know how to get lines from a file with mapreduce by setting FileInputFormat.setInputPath(job, new Path(inputFile));
But I don't understand how I can get lines of each file of a folder.
Once I have those lines in my mapper, how can I access to the filename corresponding, so that I can create the data I want ?
Thank you for your consideration.
Ambre
You do not need map-reduce in your situation. That's because you want to preserve the order of lines in result file. In this case single thread processing will be faster.
Just run java client with code like this:
FileSystem fs = FileSystem.get();
OutputStream os = fs.create(outputPath); // stream for result file
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os));
for (String inputFile : inputs) { // reading input files
InputStream is = fs.open(new Path(inputFile));
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
pw.println(line);
}
br.close();
}
pw.close();
I have put some values in a file. In the puppet manifests I want to get the value of these variables. Is there a specific directory to put my file? Also, what should be the format of the file?
If this file on puppet-server, you can write functions for module. For example:
modules/my_module/lib/puppet/parser/functions/get_var.rb:
$: << File.expand_path(File.join(File.dirname(__FILE__), '.'))
module Puppet::Parser::Functions
newfunction(:get_var,
:type => :rvalue) do |args|
file_name = args[0]
f = File.open(file_name)
s = f.readline()
return s
end
end
And use it in manifests: $test = get_var('/etc/puppet/configs.txt'). This function return first string from file, but you can change it for your needs.
For file on client, you can write facter.
I need to read data from a text file line by line. Each line contains either a string or an integer. I want to use StreamReader to read line by line from the text file and StreamWriter to write it to a binary file. The "write to binary file" part will be easy. The "read from text file line by line" part is the part I need help with.
It's all built into StreamReader:
using (var sr = new StreamReader(myFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// line is the text line
}
}
In c# you can do something like this.
string loc = "idk/where/ever";
using(var sr = new StreamReader(loc))
using(var sw = new StreamWriter(loc+".tmp"))
{
string line;
while((line=sr.ReadLine())!=null)
{
sw.WriteLine(line);
//edit it however you want
}
}
File.Delete(loc);
File.Move(loc+".tmp",loc);