#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2011
    Posts
    5
    Rep Power
    0

    How to create another file?


    I have a file that contains following data:

    100|ABC
    200|EF
    400|ACD
    500|A

    Want to create another file from the above file like this:

    100|A
    100|B
    100|C
    200|E
    200|F
    400|A
    400|C
    400|D
    500|A


    How is this accomplished in Unix?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,367
    Rep Power
    1870
    What tools do you know?
    What tools are you allowed to use?

    The general progression for working with text on Unix systems is
    - grep
    - sed
    - awk
    - perl

    Here's a teaser (xsel is just a program which copies the clipboard to stdout)
    Code:
    $ xsel | awk -F'|' '{ print $1 "|" substr($2,0,1) }'
    100|A
    200|E
    400|A
    500|A
    Perhaps you could do a bit of reading on awk, find out how to make a loop and extract each character of $2
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2011
    Posts
    5
    Rep Power
    0
    I can use grep,awk and sed.
  6. #4
  7. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,367
    Rep Power
    1870
    > I can use grep,awk and sed.
    Good - you have all you need to make an attempt of your own.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2007
    Posts
    47
    Rep Power
    20
    Code:
    awk -F'|' -v OFS='|' ' { $2=" "$2; while(sub(".","",$2) && $2 ) print $1,substr($2,1,1) } '  input_file
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    1
    Rep Power
    0
    awk 'BEGIN{FS="|"}{ for(i=1;i<=length($2);i++){ x=substr($2,i,1); printf("%d|%s\n",$1,x);}}' input_file

IMN logo majestic logo threadwatch logo seochat tools logo