Results 1 to 6 of 6
  1. #1
    Join Date
    Jun 2004
    Posts
    46

    Unanswered: Trim Function ??

    Hi !

    Is there any cmd to trim the leading and trailing spaces in fields in a file seperated with commas

    if i have

    1, 3 , 45 , ert , mj

    then output should be
    1,3,45,ert,mj

    thanks
    Mark.

  2. #2
    Join Date
    Apr 2004
    Location
    Boston, MA
    Posts
    325
    nawk -f mark.awk myFile.txt

    here's mark.awk:

    Code:
    BEGIN {
      FS=OFS=","
    }
    
    function trim(str)
    {
      sub("^[ ]*", "", str);
      sub("[ ]*$", "", str);
      return str
    }
    
    {
      for(i=1; i <= NF; i++)
        printf("%s%s", trim($i), (i==NF) ? "\n" : OFS);
    }
    vlad
    +-----------------------+
    | #include <disclaimer.h> |
    +-----------------------+

  3. #3
    Join Date
    Aug 2004
    Location
    Rome, Italy
    Posts
    81

    Smile

    manualy you can do it like this:

    ex file.txt <<EOF
    %s/ ,/,/g <<EOF
    wq <<EOF

    Or inside of a script you can use sed like this:

    sed -e '%s/ ,/,/g' file.txt >file.tmp
    mv file.tmp file.txt

    bye bye,
    ducasio

  4. #4
    Join Date
    Apr 2004
    Location
    Boston, MA
    Posts
    325
    or
    Code:
    sed -e 's/[ ][ ]*,/,/g;s/,[ ][ ]*/,/g' myFile.txt
    vlad
    +-----------------------+
    | #include <disclaimer.h> |
    +-----------------------+

  5. #5
    Join Date
    Jun 2004
    Posts
    46
    Thanks,

    but for in the sed command, if my input contains strings as below then it won't work

    1 , ' jason ', 3

    output
    1,'jason',3

    i can do this with awk , but with the sed cmd is there any way to do the above

    Thanks again for your answers

    thanks
    Mark

  6. #6
    Join Date
    Apr 2004
    Location
    Boston, MA
    Posts
    325
    I think if you try my sed solution, it should give you what I [bold]think[/bold] you want.
    vlad
    +-----------------------+
    | #include <disclaimer.h> |
    +-----------------------+

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •