Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux - Only find a pattern within a line, not the whole line

Tags:

regex

linux

bash

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

like image 876
MiketheCalamity Avatar asked Apr 04 '14 23:04

MiketheCalamity


People also ask

How to find a particular pattern in linux files?

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.

How do you search for a specific line in Unix?

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 .

How do I display a specific line in a file in Linux?

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.

How do you grep the nth line after a match?

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.


1 Answers

you were close, you need the -o flag

grep -o 'Xx.*yY' <<<AAAAAAAAAAAAAXxXxXxXxBananasyYyYyYyYBBBBBBBCCCCCC
XxXxXxXxBananasyYyYyYyY
like image 199
iruvar Avatar answered Nov 15 '22 20:11

iruvar