Get entire text line that starts with search pattern

grep
powershell get a specific line of content from a text file
grep print line containing text
powershell extract lines containing string
grep examples
powershell find line number of string in text file
powershell find string in text file
powershell extract lines from text file

I have a .txt file full of lines that each start with a unique id in square brackets:

[13] Text text text text text text text
[23] Text text text text text text text
[65] Text text text text text text text
[07] Text text text text text text text 
[66] Text text text text text text text

With php I open and retrieve the text file content:

$file = 'path_to_file/file.txt';
$handle = fopen($file, "r");
$content = fread($handle, filesize($file));
fclose($handle);

$search_id = '[65]';

I now wish to find the individual line in $content that starts with the id I am searching for ($search_id), and retrieve only that line. The id's in square brackets (followed by a space) will always initiate the lines. When retrieving the line, I wish to strip it of this id, since I only need the text line without the id.

My questions are:

  • How do I most efficiently search this file? (There will always be only one occurrence of the id)
  • How do I collect the line that contains the search key? And
  • how do I remove the leading id-and-brackets to only retrieve the text line?

Get all lines containing a string in a huge text file, Try this: get-content myfile.txt -ReadCount 1000 | foreach { $_ -match "my_string" }. That will read your file in chunks of 1000 records at a time,  The File object contains a static ReadLines method that returns line-by-line, in contrast with ReadAllLines which returns an array and thus needs to load the complete file in memory. So, by using File.ReadLines and LINQ an efficient and short solution could be written as: var found = File.ReadLines().Where(line => line.Contains("eng")).ToArray();

First of all, I suggest you use file to get an array containing the file's lines:

$file = 'path_to_file/file.txt';

$search_id = '[65]';

$lines = file($file);

$text = $textWithSearchId = '';
foreach($lines as $line)
{
    if(strpos(trim($line), $search_id) === 0)
    {
        $text = trim(substr($line, strlen($search_id)));
        $textWithSearchId = $line;
    }
}
echo "$text<br />$textWithSearchId";

Here is a working test:

$lines = array();
$lines[] = "[13] Text 13 text text text text text text";
$lines[] = "[23] Text 23 text text text text text text";
$lines[] = "[65] Text 65 text text text text text text";
$lines[] = "[07] Text 07 text text text text text text";
$lines[] = "[66] Text 66 text text text text text text";

$search_id = '[65]';

$text = $textWithSearchId = '';
foreach($lines as $line)
{
    if(strpos(trim($line), $search_id) === 0)
    {
        $text = trim(substr($line, strlen($search_id)));
        $textWithSearchId = $line;
    }
}
echo "$text<br />$textWithSearchId";

Output:

Text 65 text text text text text text
[65] Text 65 text text text text text text

Using Grep + Regex (Regular Expressions) to Search Text in Linux , Using Grep & Regular Expressions to Search for Text Patterns in Linux Now that you have the files, you can start working with grep . If you want to find all lines that do not contain a specified pattern, you can use the -v or --invert-match  These searches can range in complexity from simple to complicated text patterns. The following code example searches for the word "the" or "their" in a sentence, ignoring case. The static method Regex.IsMatch performs the search. You give it the string to search and a search pattern. In this case, a third argument specifies case-insensitive search.

$file = 'path_to_file/file.txt';
$handle = fopen($file, "r");
$content = fread($handle, filesize($file));
fclose($handle);
$arr = explode(PHP_EOL, $content);
$search_id = '[65]';
foreach ($arr as $value) {
    $result = substr($value, 0, 4);
    if($result === $search_id) 
    {
      $string = str_replace($search_id,'', $value);
      print_r($string);
      return;
    }
}

Variable $string contains the output

Finding Things – The Unix Shell, Use grep to select lines from text files that match simple patterns. In addition, the search pattern we have selected does not have to form a complete word, is where we want our search to start. find 's output is the names of every file and  re.search (): Finding Pattern in Text re.search () function will search the regular expression pattern and return the first occurrence. Unlike re.match, it will check all lines of the input string. It returns a match object when the pattern is found and “null” if the pattern is not found

grep(1): print lines matching pattern, -f FILE, --file=FILE: Obtain patterns from FILE, one per line. In order to improve the probability that lines from a single file will all start at the same For example, the command grep -E '{1' searches for the two-character string {1 instead of  A regular expression is a pattern that describes a set of strings. * is one of the key patterns in regular expressions. By default, grep interprets it as follows: * The preceding item will be matched zero or more times. This means that your pattern as it stands, ^** does not make much sense.

Regex Examples: Matching Whole Lines of Text That Satisfy Certain , Often, you want to match complete lines in a text file rather than just the part of the This is useful if you want to delete entire lines in a search-and-replace in a Again, the anchors must match at the start and end of a line and the dot must For the positive lookahead, we only need to find one location where it can match. The Get-Command cmdlet sends objects down the pipeline to the Out-File to create the Command.txt file in the current directory. Select-String uses the Path parameter to specify the Command.txt file. The Pattern parameter specifies Get-Computer as the search pattern.

Searching for Patterns With grep, To search for a particular character string in a file, use the grep command. For example, to find Edgar Allan Poe's telephone extension, type grep , all or part of The following command finds any line in the file list that starts with the letter b. Regex tutorial — A quick cheatsheet by examples any text by searching for one or more matches of a specific search pattern $ will match the start and end of a line, instead of the whole

Comments
  • Is the file subjected to change frequently or is it static?
  • @vivek_23 It might be changed manually now and then. The page that runs this php-code should simply retrieve the text lines every time it is run
  • Ok, so is the goal fast search?
  • If you want to retrieve fast, then have these in your DB with the ID column indexed. If you don't like it the DB way, I am afraid, line by line processing seems to be the only way.
  • Thank you. Seems to work well. The file may contain a few hundred lines. Would there be a speed issue?
  • No, even thousands should be OK. You would need to time it.
  • This seems to be the fastest as far as file reading is concerned.
  • See my edit suggestion ;) (ps. I did not downvoted)
  • I didn't downvote either but maybe because it is just a code dump with no explanation.
  • Okay but i tried to cover all the senerio I have updated the code kindly check ones
  • You rejected my edit... see it and add some text to explain your code, by doing this it'll maybe fine