3

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

1
  • 1
    try awk '{print $4 " " $6}' timetest.txt Commented Oct 15, 2015 at 12:28

5 Answers 5

3

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
1

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.

1

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
1
  • That was my though too. Only difficulty: if there are not 2 matches on every line, the output may merge matches from different lines. Commented Oct 15, 2015 at 12:54
1

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
1
  • That just prints the end of any line that contains a string that starts with time, it doesn't look for the 2 specific regexps the OP cares about.
    – Ed Morton
    Commented Oct 15, 2015 at 13:16
0
awk -vRS="time[12]-[0-9]+" '{$0=RT}1' filename
time1-12
time2-13
time1-14
time2-15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.