Results 1 to 7 of 7
suppose i want to find a pattern with grep, sed or awk,is there any way by which i can print what is in the right hand side of that pattern ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
- 12-28-2005 #1Just Joined!
- Join Date
- Dec 2005
- Location
- Assam, India
- Posts
- 36
string manipulation
suppose i want to find a pattern with grep, sed or awk,is there any way by which i can print what is in the right hand side of that pattern till the end of the line omitting the left side
- 12-28-2005 #2Linux Newbie
- Join Date
- Oct 2004
- Posts
- 158
Please give us a simple example:
Your regalar expression
expected input
expected output
Your explanation is not clear at all.
- 12-28-2005 #3Just Joined!
- Join Date
- Dec 2005
- Location
- Assam, India
- Posts
- 36
oh i have found that out. but now i am stuck in something else.
if i want to print just the 2nd or 3rd or in general the nth occurance of a pattern is it possible to do it?
let me give an example. suppose the file 'sample.txt' contains the following lines:
this is line no.1
this is line no.2
this line contains the pattern
this is line no.4
this is line no.5
even this line contains the pattern
this is line no.7
do not forget this line for pattern
this is line no.9
grep 'pattern' sample.txt
will print all the lines viz.:-
this line contains the pattern
even this line contains the pattern
do not forget this line for pattern
Now if I want to find the second occurance of 'pattern' is there any way to do it?
i.e. just the line
even this line contains the pattern
- 12-28-2005 #4Linux Guru
- Join Date
- Oct 2001
- Location
- Täby, Sweden
- Posts
- 7,578
The most obvious (to me) method would be something like this:
Just change -n+2 to -n+3 or -n+4 or whatever occurance you wantCode:grep pattern | tail -n+2 | head -n1
- 12-28-2005 #5Linux Guru
- Join Date
- Oct 2001
- Location
- Täby, Sweden
- Posts
- 7,578
On another note, if you want to save all the occurances by position to be able to reference them later, you can use a bash array, like this:
Code:IFS=$'\n' res=($(grep pattern sample-file)) echo "Number of occurances found: ${#res[@]}" echo "The first occurance was \"${res[0]}\", and the third was \"${res[2]}\"" echo "In order, the occurances were:" for r in "${res[@]}"; do echo " $r"; done
- 12-30-2005 #6Just Joined!
- Join Date
- Dec 2005
- Location
- Assam, India
- Posts
- 36
thanks dolda, i didn't know head and tail had such nice options.
there lies the beauty and power of linux. by combining simple commands we can perform some mammoth tasks.
- 12-31-2005 #7Linux Engineer
- Join Date
- Feb 2005
- Posts
- 1,044
That's the way UNIX was designed back in the late 60s! It's stood the test of time, wouldn't you say?


Reply With Quote
