LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   break word into individual alphabets (https://www.linuxquestions.org/questions/linux-newbie-8/break-word-into-individual-alphabets-932474/)

sysmicuser 03-03-2012 04:49 AM

break word into individual alphabets
 
Hi all,

I am looking "ideally" into a sed one line which would do magic such as follows..

input: Oneword
Output:'O','n','e','w','o','r','d','\0'

At end of each word split, it should have '\0' is there any quick and samrt way with sed or any other language?

colucix 03-03-2012 05:10 AM

An awk solution:
Code:

$ echo Oneword | awk 'BEGIN{FS=""}{for (i=1;i<=NF;i++) printf "\x27%s\x27,",$i}END{print "\x27\\0\x27"}'
'O','n','e','w','o','r','d','\0'

The Field Separator set to the empty string take charge of splitting the string into individual characters. "\x27" is the hex code of the single quote.

sysmicuser 03-03-2012 05:22 AM

@colucix

Simply superb !!

I need sometime to digest this deliciious meal though :)

grail 03-03-2012 09:09 AM

Just for something slightly different:
Code:

echo Oneword | awk -F "" '{q="\047";$1=$1; print q$0q",\\0"q}' OFS="','"

sysmicuser 03-15-2012 07:07 AM

@colucix and @frail.

This is simply fascinating, I am truly mesmerized by the beauty of awk ! :)

Can you please explain me login in your awk one liners? I am still learning so your help would be highly appreciated.

Thank you

danielbmartin 03-15-2012 10:45 AM

I will contribute a sed solution.

Input file:
Code:

nowisthetime
forallgoodmen
tocometotheaid
oftheirparty

Code:
Code:

sed "s/./&\',\'/g;s/^/\'/;s/$/\\\0\'/" $InFile > $OutFile
Output file:
Code:

'n','o','w','i','s','t','h','e','t','i','m','e','\0'
'f','o','r','a','l','l','g','o','o','d','m','e','n','\0'
't','o','c','o','m','e','t','o','t','h','e','a','i','d','\0'
'o','f','t','h','e','i','r','p','a','r','t','y','\0'

Explanation:
Starting with this: nowisthetime
we execute this: s/./&\',\'/g
to produce this: n','o','w','i','s','t','h','e','t','i','m','e','

That's a good intermediate result but we need to "dress up" the
beginning and end of each line, so ...

Then we execute this: s/^/\'/
to prefix each line with a single quote mark
to produce this: 'n','o','w','i','s','t','h','e','t','i','m','e','

Finally, we execute this: s/$/\\\0\'
to suffix each line with \0'
to produce the desired result: 'n','o','w','i','s','t','h','e','t','i','m','e','\0'


Daniel B. Martin

sysmicuser 03-15-2012 07:36 PM

Absolutely fantatstic solution Daniel :)


All times are GMT -5. The time now is 12:03 PM.