Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

AWK (Extract Chacacters) 1

Status
Not open for further replies.

MIKENY1

IS-IT--Management
Feb 4, 2003
2
US
I have the following text line:

The Physical Memory is 536870912 bytes

I would like to extract the 24th Character to the 33rd Character. The end result would extract 536870912 from the string.

Is this possible with Awk ?

Any help would be greatly appreciated.

Thanks.

 
Yep:
a="The Physical Memory is 536870912 bytes"
echo $a | awk ' {
print substr($0,24,33)
}
 
nawk '{print $(NF-1)}' vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Hmm..
Well as long as we don't worry about doing
it the way it was requested originally(that
is by string indexes)we can do all kinds of
squirrely things..
Code:
gawk '{gsub(/[^0-9]+/,&quot;&quot;,$0) ; print}' 
gawk '{split($0,arr) } END { print arr[5] } '

WE can get absurd:
gawk '
function stoopid(str,allnums, cnt,x,i,mystr,array) {
z  = split(str,array,&quot;&quot;)
  for (i=1 ; i <= z ; i++) {
    for (x in allnums) {
        if (array[i] == allnums[x]) {
           cnt++
           mystr = length(mystr) < 1 ? array[i] : mystr array[i]
        }
    }
  }
print mystr
return cnt
}
BEGIN {
str=&quot;This is a test of the 5678909 MB of RAM in my machine&quot;
 for (p=0 ; p <= 9 ; p++) {
   all[r++] = p
}
stoopid(str,all)
}'
But why bother if substr() is available?
 
marsd,
you're right - the OP requested a solution with the substr usage. I've simply noted an alternative solution for the 'well-behaved' data stream.

While my alternative assumes the data is 'well-behaved', so does the substr approach. Personally I try to stay away from using the substr whenever I can as I find it a bit less 'tolerant/permissive' for changes in the data stream.

But that's just me - your mileage may vary.

vlad vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top