[ Home  |  FAQ-Related Q&As  |  General Q&As  |  Answered Questions ]


    Search the Q&A Archives


...equivalent function from "trim" or "rtrim" or...

<< Back to: comp.lang.awk FAQ

Question by pierric
Submitted on 7/20/2003
Related FAQ: comp.lang.awk FAQ
Rating: Rate this question: Vote
Is there any equivalent function from "trim" or "rtrim" or ltrim" ?


Answer by rockmelon
Submitted on 9/8/2003
Rating:  Rate this answer: Vote
gsub is your friend:

ltrim(v) = gsub(/^[ \t]+/, "", v)
rtrim(v) = gsub(/[ \t]+$/, "", v)
trim(v)  = ltrim(v); rtrim(v)

 

Answer by khom
Submitted on 7/26/2005
Rating: Not yet rated Rate this answer: Vote
# EXAMPLE:
# echo "    ltrim    ,    rtrim    ,    trim    " | awk -F',' -f trim.awk
function ltrim(v)
{
   gsub(/^[ \t]+/, "", v);
   return v;
}
function rtrim(v)
{
   gsub(/[ \t]+$/, "", v);
   return v;
}
function trim(v)
{
   return ltrim(rtrim(v));
}
{
   print "[" ltrim($1) "] [" rtrim($2) "] [" trim($3) "]"
}

 

Answer by hansmuff
Submitted on 8/23/2005
Rating: Not yet rated Rate this answer: Vote
gsub works perfectly fine. The following may be faster, depending on the awk interpreter:

function trim (string, what,   ret) {
   ret = rtrim(string, what)
   ret = ltrim(ret, what)
   return ret
}   
function rtrim (string, what,   ret) {
   ret = string
   while (substr(ret, 1, 1) ~"[" what "]")
      ret = substr(ret, 2)
   return ret
}
function ltrim (string, what,   ret) {
   ret = string
   while (substr(ret, length(ret), 1) ~"[" what "]")
      ret = substr(ret, 1, length(ret) - 1)
   return ret
}

 

Your answer will be published for anyone to see and rate.  Your answer will not be displayed immediately.  If you'd like to get expert points and benefit from positive ratings, please create a new account or login into an existing account below.


Your name or nickname:
If you'd like to create a new account or access your existing account, put in your password here:
Your answer:

FAQS.ORG reserves the right to edit your answer as to improve its clarity.  By submitting your answer you authorize FAQS.ORG to publish your answer on the WWW without any restrictions. You agree to hold harmless and indemnify FAQS.ORG against any claims, costs, or damages resulting from publishing your answer.

 

FAQS.ORG makes no guarantees as to the accuracy of the posts. Each post is the personal opinion of the poster. These posts are not intended to substitute for medical, tax, legal, investment, accounting, or other professional advice. FAQS.ORG does not endorse any opinion or any product or service mentioned mentioned in these posts.

 

<< Back to: comp.lang.awk FAQ


[ Home  |  FAQ-Related Q&As  |  General Q&As  |  Answered Questions ]

© 2008 FAQS.ORG. All rights reserved.