Mahesh Suranagi
Mahesh Suranagi

Reputation: 29

How to search for a pattern in a line and print data which is present after that pattern in that line

I have file which has uneven lines as below:

jacktyutu/ABC/uyiyi/yyuiyiu/1.java
adhjasgdhg/gsdjgf/ABC/sdfhgsdfj/sdjfhsd/sdfkjhsdkf/2.java
adhjasgdhg/01/ABC/sdfhgs/213/j/sdjfhsd/sdfkjhsdkf/3.java
sd/asd/asd/ABC/sdjg/76/987/4.java

From the above file I want to search for the pattern ABC from each line and print the rest of the data from that line for ex

My output should be as below:

uyiyi/yyuiyiu/1.java
sdfhgsdfj/sdjfhsd/sdfkjhsdkf/2.java
sdfhgs/213/j/sdjfhsd/sdfkjhsdkf/3.java
sdjg/76/987/4.java

How to achieve this in shell script or with awk and sed?

Upvotes: 0

Views: 2000

Answers (5)

Arif Burhan
Arif Burhan

Reputation: 505

A perl oneliner:

    perl -e "/ABC/;print $';"

_

    print $` 

prints everything before the match, and

    print $& 

prints the matched characters, useful if you are matching against a pattern (Regular Expression).

A modern version of sed or awk may have the special $ variables, but I have not seen any.

Upvotes: 0

twalberg
twalberg

Reputation: 62379

Obligatory bash version:

found_something=false
while read line
do
  [[ "${line}" =~ ABC/ ]] && echo "${line#*ABC/}" && found_something=true
done < file
${found_something} || echo "I didn't find any lines matching ABC/"

Edit: added a few lines to handle the case of the target string not being present...

Upvotes: 0

brianadams
brianadams

Reputation: 233

Only if you have one ABC in each line

perl -F"\/ABC\/" -ane 'print $F[1];' file

Upvotes: 1

Kent
Kent

Reputation: 195059

From the above file I want to search for the pattern ABC from each line and print the rest of the data from that line for ex...

I would do:

 grep -Po '.*?ABC/\K.*' file

this works if one line containing multiple ABC/, it picks only the rest stuff after the 1st ABC/. if it is required.

see test:

kent$  cat f
jacktyutu/ABC/uyiyi/yyuiyiu/1.java
adhjasgdhg/gsdjgf/ABC/sdfhgsdfj/sdjfhsd/sdfkjhsdkf/2.java
adhjasgdhg/01/ABC/sdfhgs/213/j/sdjfhsd/sdfkjhsdkf/3.java
sd/asd/asd/ABC/sdjg/76/987/4.java
foo/ABC/___here/ABC/comes again

kent$  grep -Po '.*?ABC/\K.*' f
uyiyi/yyuiyiu/1.java
sdfhgsdfj/sdjfhsd/sdfkjhsdkf/2.java
sdfhgs/213/j/sdjfhsd/sdfkjhsdkf/3.java
sdjg/76/987/4.java
___here/ABC/comes again

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85785

With GNU Grep:

$ grep -oP "(?<=ABC/).*" file
uyiyi/yyuiyiu/1.java
sdfhgsdfj/sdjfhsd/sdfkjhsdkf/2.java
sdfhgs/213/j/sdjfhsd/sdfkjhsdkf/3.java
sdjg/76/987/4.java

With awk:

$ awk -F'ABC/' '{print $2}' file
uyiyi/yyuiyiu/1.java
sdfhgsdfj/sdjfhsd/sdfkjhsdkf/2.java
sdfhgs/213/j/sdjfhsd/sdfkjhsdkf/3.java
sdjg/76/987/4.java

With sed:

$ sed 's%.*ABC/%%' file
uyiyi/yyuiyiu/1.java
sdfhgsdfj/sdjfhsd/sdfkjhsdkf/2.java
sdfhgs/213/j/sdjfhsd/sdfkjhsdkf/3.java
sdjg/76/987/4.java

Upvotes: 1

Related Questions