I want to use a regex to find a pattern in a file. That pattern may be in the middle of a line, but I don't want the whole line. I tried grep -a pattern file
but this returns the entire line that contains the regex. The following is an example of what I'm trying to do. Does anyone know a way to do this?
Example:
Input: AAAAAAAAAAAAAXxXxXxXxBananasyYyYyYyYBBBBBBBCCCCCC
Regex: Xx.*yY
Ouput: XxXxXxXxBananasyYyYyYyY
To find a pattern that is more than one word long, enclose the string with single or double quotation marks. The grep command can search for a string in groups of files. When it finds a pattern that matches in more than one file, it prints the name of the file, followed by a colon, then the line matching the pattern.
To do this, press Esc , type the line number, and then press Shift-g . If you press Esc and then Shift-g without specifying a line number, it will take you to the last line in the file. To look for the next occurrence after the first, either press n or press / again and then press Enter .
Using the head and tail Commands Let's say we want to read line X. The idea is: First, we get line 1 to X using the head command: head -n X input. Then, we pipe the result from the first step to the tail command to get the last line: head -n X input | tail -1.
To get the n-th line after each match, we can first use grep -An to find each block with n+1 lines. Next, instead of piping it to grep -v, we pipe it to a command that can print every (n+1)-th line. As the output above shows, we've got the 3rd line after each “Performance: BAD” line.
you were close, you need the -o
flag
grep -o 'Xx.*yY' <<<AAAAAAAAAAAAAXxXxXxXxBananasyYyYyYyYBBBBBBBCCCCCC
XxXxXxXxBananasyYyYyYyY
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With