Thursday, April 3, 2008

Shell script problem

I wanted to split a string in shell array of the from 2008032800 to something like 2008 03 28 00. But as it seems this is extremely difficult to do using shell scripts! I tried in vain using grep and cut :'(
This is as close as I got
echo "2008032800" | grep "^.\{2\}"

Interestingly grep when match a part of a string, it continues to rip it off from the original text and remaining part is used again to match the regex! I wonder whether that is the correct thing to do!

2 comments:

Dilan Anuruddha said...

Gav provided this links which solve the initial problem
http://unix-simple.blogspot.com/2006/10/awk-substr-function.html

Dilan Anuruddha said...

Ok here is how u do it! :)

echo "2008032800" | awk '{ printf("%s-%s-%s %s", substr($1,1,4),substr($1,5,2),substr($1,7,2),substr($1,9,2)) }'