Finding Lines in a Text File Matching a Regular Expression

How to display all lines in file that matching a regular expression?

You need to read the file

const fs = require("fs");
const text = fs.readFileSync("./mytext.txt");
const textByLine = text.split("\n")
textByLine.forEach( line => {
if (line.match('/error/gi'))
{
console.log(line);
}

});

RegEx: Search string at certain line of (text-)file

There is a regex approach but you might want to split your text with split('\n') (or similar depending on the language).

Anyway you'll have what you're looking for with:

^(?<!\n)(?:.*?\n){2}[^\n]*?(line)
  • ^ ensure we start at the beginning of a line
  • (?<!\n) is a negative lookbehind to make sure the current line is not preceeded by another one (i.e. we start counting from the first line)
  • (?:...) delimits a non capturing group. It's not the relevant part of the match
  • .*?\n matches any character until a line break is met (? makes the expression lazy instead of greedy)
  • {2} is the numer of line breaks you want to count (basically your line number minus 1)
  • .*?(line) matches any character until the next occurrence of "line"

See here: https://regex101.com/r/JIRkpN/1

Regular expression to get the first match in a text file

ROOT$ requires the four characters ROOT adjacent to the end of the line. findall returns all matches; if you only care about the first, probably simply use match or search.

with open(file, 'r', encoding='utf-8', errors='ignore') as f:
for line in f:
m = re.match(r'(\d+)\|ROOT', line)
if m:
print(m.group(1))
break

The break causes the loop to terminate as soon as the first match is found. We read one line at a time until we find one which matches, then terminate. (This also optimizes the program by avoiding the unnecessary reading of lines we do not care about, and by avoiding reading more than one line into memory at a time.) The parentheses in the regex causes the match inside them to be captured into group(1).

How can I get only the first line in a file that starts with 1. followed by any character except a number?

With your shown samples, please try following grep code. Simple explanation would be: Using grep's m1 option to print only first match and exit from program then in main program mentioning regex to match lines that start from 1. followed by a non-digit character, if match is found then print the line.

grep -m1 '^1\.[^0-9]'  Input_file

Extract lines with a matching pattern in log file delimited by some characters

This awk should do the job:

awk '/^MATNR/ {m=$0} /Return Message/ {print m, $0}' file

MATNR -- 0000000000090933887 *****Return Message** Successfully processed
MATNR-000000000000090934206 *****Return Message** Successfully processed


Related Topics



Leave a reply



Submit