user1492786
user1492786

Reputation: 53

Strings extraction from text file with sed command

I have a text file which contains some lines as the following:

ASDASD2W 3ASGDD12 SDADFDFDDFDD W11 ACC=PNO23 DFSAEFEA EAEDEWRESAD ASSDRE 
AERREEW2 3122312 SDADDSADADAD W12 ACC=HH34 23SAEFEA EAEDEWRESAD ASEEWEE 
A15ECCCW 3XCXXF12 SDSGTRERRECC W43 ACC=P11 XXFSAEFEA EAEDEWRESAD ASWWWW 
ASDASD2W 3122312 SDAFFFDEEEEE SD3 ACC=PNI22 ABCEFEA EAEDEWRESAD ASWEDSSAD 
...

I have to extract the substring between the '=' character and the following blank space for each line , i.e.

PNO23
HH34
P11
PNI22

I've been using the sed command but cannot figure out how to ignore all characters following the blank space.

Any help?

Upvotes: 2

Views: 5810

Answers (6)

Sisay Chala
Sisay Chala

Reputation: 141

A chain of grep can do the trick.

grep -o '[=][a-zA-Z0-9]*' file | grep -o '[a-zA-Z0-9]*'

Upvotes: 0

potong
potong

Reputation: 58558

This might work for you:

sed -n 's/.*=\([^ ]*\).*/\1/p' file

or, if you prefer:

sed 's/.*=\([^ ]*\).*/\1/p;d' file

Upvotes: 1

Jo So
Jo So

Reputation: 26531

Sorry, but have to add another one because I feel the existing answers are just to complicated

sed 's/.*=//; s/ .*//;' inputfile

Upvotes: 2

Dennis Williamson
Dennis Williamson

Reputation: 360625

sed 's/[^=]*=\([^ ]*\) .*/\1/' inputfile

Match all the non-equal-sign characters and an equal sign. Capture a sequence of non-space characters. Match a space and the rest of the line. Substitute the captured string.

Upvotes: 0

tripleee
tripleee

Reputation: 189830

Put the string you want to capture in a backreference:

sed 's/.*=\([^ =]*\) .*/\1/'

or do the substitution piecemeal;

sed -e 's/.*=//' -e 's/ .*//'

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799320

Use the right tool for the job.

$ awk -F '[= ]+' '{ print $6 }' input.txt
PNO23
HH34
P11
PNI22

Upvotes: 2

Related Questions