The UNIX Cut Command only certain characters

August 19, 2011 at 12:45:12
Specs: Sun Solaris
I have a file like so:
600507680583102C3700000000000031Cd0s4
60050758618102C3700000000000031Ed0s4
c6t6005772268018102C37000000000000180d0s4
c6t6005058383018102C37000000000000181d0s4

I want to cut or print only the 4 digits before the "d0s4" of each line. Is there a way to cut previous lines not the lines in front of "d0s4"?


See More: The UNIX Cut Command only certain characters

Report •

#1
August 19, 2011 at 23:26:18
Use awk's internal index function to find out where "d0s4" is in the line. Backup 4 positions, and use the internal substr function to return the 4 required characters:

#!/bin/ksh


awk ' {

   # find out where the d0s4 string is
   retval=index($0, "d0s4")

   if(retval > 0)
      {
      retstr=substr($0, (retval - 4), 4)
      print retstr
      }

} ' data.txt


Report •
Related Solutions


Ask Question