Tiny Rick
Tiny Rick

Reputation: 276

Grep more than one string in a single line

I am trying to locate two strings in a single line. Below is the example line.

line1: xxxx yyyy time1-12 zzzz time2-13
line2: xxxx yyyy time1-14 zzzz time2-15

I am using the below grep command to achieve this

grep -o -E 'time1-[0-9]*|time2-[0-9]*' timetest.txt

This is giving me the output as

time1-12
time2-13
time1-14
time2-15

But i want like this

time1-12 time2-13
time1-14 time2-15

What i am missing here? Can i go for awk or sed for getting this output

Upvotes: 3

Views: 882

Answers (5)

bian
bian

Reputation: 1456

awk -vRS="time[12]-[0-9]+" '{$0=RT}1' filename
time1-12
time2-13
time1-14
time2-15

Upvotes: 0

Kalanidhi
Kalanidhi

Reputation: 5092

Try this sed command ,

sed 's/[^t]\+\(time[^ ]\+\)/\1 /g' FileName

or

sed 's/[^t]\+\(time\(1\|2\)[^ ]\+\)/\1 /g' FileName

OutPut:

time1-12 time2-13 
time1-14 time2-15

Cut version

cut -d" " -f 4,6 FileName

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203502

With GNU awk for the 3rd arg to match():

$ awk 'match($0,/time1-[0-9]*/,a) && match($0,/time2-[0-9]*/,b) { print a[0], b[0] }' file
time1-12 time2-13
time1-14 time2-15

Note that time1 and time2 can be in any order on the line. With other awks you need to use substr() to extract the match() results:

$ awk 'match($0,/time1-[0-9]*/) && (a=substr($0,RSTART,RLENGTH)) && match($0,/time2-[0-9]*/) { print a, substr($0,RSTART,RLENGTH) }' file
time1-12 time2-13
time1-14 time2-15

If the 2 times are always in the same order then with gawk you could do:

$ awk 'match($0,/(time1-[0-9]*).*(time2-[0-9]*)/,a) { print a[1], a[2] }' file
time1-12 time2-13
time1-14 time2-15

but then it's just a simple substitution on an individual line so you may as well just use sed:

$ sed -r 's/.*(time1-[0-9]*).*(time2-[0-9]*).*/\1 \2/' file
time1-12 time2-13
time1-14 time2-15

Upvotes: 3

Jose Ricardo Bustos M.
Jose Ricardo Bustos M.

Reputation: 8164

Another solution, using grep

grep -o -E 'time[0-9]+-[0-9]+' timetest.txt | paste -d " " - -

you get,

time1-12 time2-13
time1-14 time2-15

Upvotes: 1

choroba
choroba

Reputation: 241868

Perl to the rescue:

perl -lne 'print "$1 $2" if /(time1-[0-9]+).*(time2-[0-9]+)/' timetest.txt

The code assumes time1 comes always before time2.

Upvotes: 1

Related Questions