Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read first line of text file then pass following lines to a loop to read

Tags:

powershell

I need to read the first line of a file and then the subsequent lines I want read using a loop.

eg:

Read in first line
Do stuff with the data

foreach ($line in $remainingLines)
{
    more stuff
}

I have a rather messy way to achieve this but there must be a better way.

like image 835
RichGK Avatar asked Oct 23 '12 14:10

RichGK


People also ask

How do I read the first line of a text file?

A common task for a program is to read data from a file. To read from a text file in C, you will need to open a file stream using the fopen() function. Once a file stream has been opened, you can then read the file line by line using the fgets() function. Both the fopen() and fgets() functions are declared in stdio.

How do I read the first line of a text file in Python?

To read the first line of a file in Python, use the file. readline() function. The readline() is a built-in function that returns one line from the file. Open a file using open(filename, mode) as a file with mode “r” and call readline() function on that file object to get the first line of the file.

How do I skip the first line of a text file?

You can use readlines()[n:] to skip the first n line(s).


2 Answers

Assign the content of the file to two variables. The first one will hold the first line, and the second variable gets the rest. Then loop over $remainingLines.

$firstLine,$remainingLines = Get-Content foo.txt
like image 173
Shay Levy Avatar answered Sep 21 '22 11:09

Shay Levy


$contents = gc .\myfile.txt

write-host $contents[0]

for ($i=1; $i -lt $contents.Length; $i++)
{
  write-host $contents[$i]
}
like image 6
aphoria Avatar answered Sep 19 '22 11:09

aphoria