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!

Need to grab a substr in a file

Status
Not open for further replies.

pmcmicha

Technical User
May 25, 2000
353
I have a text file delimited by pipes from a database. I need to make certain modifications to these files.

FILE:

Field 1:Field 2:Field 3:Field 4:Field 5

xxxxxxx|xxxxxxx|/x/x/xx|xxxxxxx|xxxxxxx|


I need to remove the scatter path in Field 3 so that only the last entry in "/x/x/xx" exists in the new file.

FILE2:

xxxxxxx|xxxxxxx|xx|xxxxxxx|xxxxxxx|


I thought that I might be able to run with substr, but I have been unsuccessful so far. I am looking for a command that can be called with a ksh script.

This is what I have tried so far:

awk '{ $2 = substr($0, ("/")+1, $2)); print $0 }' ${FILE} > ${FILE2} # Doesn't error, but doesn't work either.

This one should work according to someone else I have been working with regarding this awk statement, but I think that you have to define the function "lastindexof"?

awk '{ $2 = substr(lastindexof("/")+1, $2)); print $0 }' ${FILE} > ${FILE2} # Always errors out.


Could someone please point in the right direction on this? Thanks in advance.
 

I assume your example should use $3 rather than $2.

If the characters to be removed only occur in field 3, use

awk '{gsub(/\/.*\//,"");print}' file1 > file2

If they can also occur in other fields, use

awk 'BEGIN{FS=OFS="|"}{gsub(/\/.*\//,"",$3);print}' file1 > file2 CaKiwi

"I love mankind, it's people I can't stand" - Linus Van Pelt
 
Code:
function getlastsepStr(s,c,max, arr,p,i,line,cnt) {
cnt = split(s,arr,"")
incnt = 0
    printf "Length of field is %d\n", cnt
    for (i=1 ; i <= cnt ; i++) {
         if (arr[i] == c) {
             #printf &quot;Found match at %d, %c\n&quot;, i, arr[i]
             incnt++
          }
          if (arr[i] == c && incnt == max) {
             for (p=(i + 1) ; p <= cnt ; p++) {
                  line = length(line) < 1 ? arr[p] : line arr[p]
              }
          }
     }
return line
}

Call it like:
mystr = getlastsepStr($3,&quot;/&quot;,2)
$3 = mystr

Or like cakiwi suggests:
function cheatit(s) {
gsub(/.*\/.*\//,&quot;&quot;,s)
return s
}
 
a variation on the same theme (not tested):

awk 'BEGIN{FS=OFS=&quot;|&quot;}{n=split($3, arr,&quot;/&quot;);$3=arr[$n];print}' file1 > file2 vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top