Get the first x lines of a File - crystal-lang

I'm trying to get the first 10 lines from a file into a string and write them to another file.
I've got:
File.open("read_file.txt", "r") do |rf|
File.open("write.txt", "w") do |wf|
rf.each_line.with_index do |line, idx|
break if idx > 9
wf.puts(line)
end
end
end
Is there a more elegant and efficient way to break on a specified number of lines
Ideally something like file.lines(3) : String would be nice but that certainly isn't available.

Here is a more elegant way (but with the same efficiency, I believe)
File.open "read_file.txt" do |io|
File.write "write.txt", io.each_line.first(10).join("\n")
end

Read the lines of the file with File#read_lines and then take the first 10 lines:
File.read_lines("file")[0..9]

Related

print all lines of a file which contain a specific string

I want to search and a log file for specific informations which are contained in the file and get the whole line printed out
for example line 32 in a .log file is:
2019-08-07 15:21:09.783 'lineid' -> 'DEU.DTAG.NBGNE00111'
I want every line printed out that includes the word lineid.
If someone could help me with my problem I would very appreciate it.
thanks
I am quite new to ruby and regex so I tried by searching something from the internet.
File.open("/Users/filip/Documents/Testcases/NG-ART_TC1054921_MKS+Results1/1054921_1042510_2242_TID-2123/TC1042510-TID2123-sequencer.log", "r") do |file|
for line in file.readlines().include? "lineid"
puts line
end
end
what I am getting back is only
/Users/filip/Documents/cucumber/features/features/step_definitions/lineid.rb:7: syntax error, unexpected end-of-input, expecting end
In ruby is recommended to use each to iterate, you don't usually use for loops.
You could try this:
File.foreach("/Users/filip/Documents/Testcases/NG-ART_TC1054921_MKS+Results1/1054921_1042510_2242_TID-2123/TC1042510-TID2123-sequencer.log").each do |line|
puts line if line.include?('lineid')
end
This will execute the given block for each line in the file without slurping the entire file into memory.
See: IO::foreach
Making your example work would look like:
File.open("/Users/filip/Documents/Testcases/NG-ART_TC1054921_MKS+Results1/1054921_1042510_2242_TID-2123/TC1042510-TID2123-sequencer.log", "r") do |file|
file.readlines().each do |line|
puts line if line.include?("erc")
end
end

Remove lines that is shorter than or equal 5 characters after the : using Notepad++

The question is like: Remove lines that is shorter than 5 characters before the # using Notepad++
But it differs a bit...
I have like that:
abc:123
abc:1234
abc:12345
PLEASE NOTE: abc is not on all the lines, it is just an example.
I want to remove the first line in the previous example because 123 which is after : is shorter than or not equal to 5 characters.
Any help would be appreciated.
Thanks!
Open Notepad++ find and replace choose regex mode in the search and place ^((?!.+:\d{5,}).)*$ in search and keep replace with blank and press replaceAll
^((?!.+:\d{5,}).)*$
Without knowing the language there is only so much help I can offer. I'll give you an example of how I would solve this problem in C#.
Start by creating a string for your updated file (without the short lines)
string content = "";
Read a line in from your file.
Then get a substring of the line you read in - the abc: portion and check the length.
line = line.substring(indexof(":"), length - indexof(":"))
if(line.length > 5)
{
content += line;
}
At the end, truncate your file and write content to it.

Find and remove specific string from a line

I am hoping to receive some feedback on some code I have written in Python 3 - I am attempting to write a program that reads an input file which has page numbers in it. The page numbers are formatted as: "[13]" (this means you are on page 13). My code right now is:
pattern='\[\d\]'
for line in f:
if pattern in line:
re.sub('\[\d\]',' ')
re.compile(line)
output.write(line.replace('\[\d\]', ''))
I have also tried:
for line in f:
if pattern in line:
re.replace('\[\d\]','')
re.compile(line)
output_file.write(line)
When I run these programs, a blank file is created, rather than a file containing the original text minus the page numbers. Thank you in advance for any advice!
Your if statement won't work because not doing a regex match, it's looking for the literal string \[\d\] in line.
for line in f:
# determine if the pattern is found in the line
if re.match(r'\[\d\]', line):
subbed_line = re.sub(r'\[\d\]',' ')
output_file.writeline(subbed_line)
Additionally, you're using the re.compile() incorrectly. The purpose of it is to pre-compile your pattern into a function. This improves performance if you use the pattern a lot because you only evaluate the expression once, rather than re-evaluating each time you loop.
pattern = re.compile(r'\[\d\]')
if pattern.match(line):
# ...
Lastly, you're getting a blank file because you're using output_file.write() which writes a string as the entire file. Instead, you want to use output_file.writeline() to write lines to the file.
You don't write unmodified lines to your output.
Try something like this
if pattern in line:
#remove page number stuff
output_file.write(line) # note that it's not part of the if block above
That's why your output file is empty.

Replace the whole string if it contains specific letters/character

Replace the whole string if it contains specific letters/character…
I have a text file (myFile.txt) that contains multiple lines, for example:
The hotdog
The goal
The goat
What I want to do is the following:
If any word/string in the file contains the characters 'go' then, replace it with a brand new word/string ("boat"), so the output would look like this:
The hotdog
The boat
The boat
How can I accomplish this in Python 2.7?
It sounds like you want something like this:
with open('myFile.txt', 'r+') as word_bank:
new_lines = []
for line in word_bank:
new_line = []
for word in line.strip().split():
if 'go' in word:
new_line.append('boat')
else:
new_line.append(word)
new_lines.append('%s\n' % ' '.join(new_line))
word_bank.truncate(0)
word_bank.seek(0)
word_bank.writelines(new_lines)
Open the file for reading and writing, iterate through it splitting each line into component words and looking for instances of 'go' to replace. Keep in list because you do not want to modify something you're iterating over. You will have a bad time. Once constructed, truncate the file (erase it) and write what you came up with. Notice I switched to sticking an explicit '\n' on the end because writelines will not do that for you.

How do I print specific lines of a file in python?

I'm trying to print everything in a file with python. But, whenever I use python's built-in readfile() function it only print the first line of my text file. Here's my code:
File = open("test.txt", 'r', 0)
line = File.readline()[:]
print line
and thank you for everyone that answers
and to make my question clearer every time I run the code it prints only "word list food
Is this what you are looking for?
printline = 6
lineCounter = 0
with open('anyTxtFile.txt','r') as f:
for line in f:
lineCounter += 1
if lineCounter == printline:
print(line, end='')
Opens text file, in working directory, and prints printLine
File.readlines()
will, as emre. said, return a list of all the lines in your file. If you'd like to produce a similar result using the readline() command,
s=File.readline()
while s!="":
print s
s=File.readline()
Both methods above leave a newline at the end of each string, except for the last string.
Another alternative would be:
for s in File:
print s
To search for a specific string, or a specific line number, I'd say the first method is best. Looking for a specific line number would be as simple as:
File.readlines()[i]
Where i is the line number you are interested in accessing. Looking for a string is a bit more work, but looping through the list would not be too challenging. Something like:
L=File.readlines()
s="yourStringHere"
i=0
while i<len(L):
if L[i].find(s)!=-1:
break
i+=1
print i
would give you the line number that contained the string you were looking for.
Make it more pythonic.
print_line = 6
with open('input_txt_file.txt', 'r') as f:
for i, line in enumerate(f):
if i == print_line:
print(line, end='')
break