I have a requirement of searching a pattern like x=<followed by any values>
from a file and displaying the pattern i.e x=<followed by any values>
, only in the screen, not the whole line. How can I do it in Linux?
Asked
Active
Viewed 64 times
-3

Alex Bogias
- 1,826
- 2
- 30
- 45

Sanghamitra Choudhury
- 17
- 1
- 2
1 Answers
1
I have 3 answers, from simple (but with caveats) to complex (but foolproof):
1) If your pattern never appears more than once per line, you could do this (assuming your shell is
PATTERN="x="
sed "s/.*\($PATTERN\).*/\1/g" your_file | grep "$PATTERN"
2) If your pattern can appear more than once per line, it's a bit harder. One easy but hacky way to do this is to use a special characters that will not appear on any line that has your pattern, eg, "@":
PATTERN="x="
SPECIAL="@"
grep "$PATTERN" your_file | sed "s/$PATTERN/$SPECIAL/g" \
| sed "s/[^$SPECIAL]//g" | sed "s/$SPECIAL/$PATTERN/g"
(This won't separate the output pattern per line, eg. you'll see x=x=x=
if a source line had 3 times "x=", this is easy to fix by adding a space in the last sed)
3) Something that always works no matter what:
PATTERN="x="
awk "NF>1{for(i=1;i<NF;i++) printf FS; print \"\"}" \
FS="$PATTERN" your_file

Fabien Viger
- 111
- 4
-
Thanks a lot Fabien for the above answer. The above methods will give only "x=" entries whereas I need the output something like , x=3 if I'm assigning x=3 and it is inside a file many times. Please let me know how do I get "x=3" output ,from a file where multiple times "x=3" is repeated inside the file? – Sanghamitra Choudhury Nov 14 '17 at 09:57
-
Some moderators have pointed to an existing answer that will work for your use case too. Applying it to your case will require knowing how the x=
is "split" from the following characters in your text files. Assuming that there is always some whitespace (possibly a newline) after the – Fabien Viger Nov 14 '17 at 23:03, this would work: `grep -oh "\w*x=\w*" your_file` -
Thanks a lot Fabien.It worked. – Sanghamitra Choudhury Nov 17 '17 at 06:07