How to split the string 201702221015
in the CCYY|MM|DD|HH|MN
format using awk, i.e. split the string 201702221015
in to 2017|02|22|10|15
?
Asked
Active
Viewed 113 times
-2

miken32
- 42,008
- 16
- 111
- 154
-
Possible duplicate of [split string to array using awk](http://stackoverflow.com/questions/8009664/split-string-to-array-using-awk) – chris g Feb 23 '17 at 03:23
4 Answers
3
One way with GNU awk for gensub():
$ awk 'BEGIN{print gensub(/(..)(..)(..)(..)$/,"|\\1|\\2|\\3|\\4",1,201702221015)}'
2017|02|22|10|15

Ed Morton
- 188,023
- 17
- 78
- 185
2
@Hanif:Try(though I am not that sure about requirement):
echo "201702221015" | awk '{print substr($0,1,4)"|"substr($0,5,2)"|"substr($0,7,2)"|"substr($0,9,2)"|"substr($0,11,2)}'

RavinderSingh13
- 130,504
- 14
- 57
- 93
2
Another solution, using gnu-awk
and FIELDWIDTHS
echo "201702221015" | awk 'BEGIN{FIELDWIDTHS = "4 2 2 2 2"; OFS="|"}$1=$1'
you get,
2017|02|22|10|15

Jose Ricardo Bustos M.
- 8,016
- 6
- 40
- 62
0
Why use awk? sed makes more sense:
echo "201702221015" | sed -E 's/([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/\1|\2|\3|\4|\5/'

miken32
- 42,008
- 16
- 111
- 154
-
3wrt `sed makes more sense` - sed only makes more sense than awk if you're calling a one-liner from the command line to do this one specific thing (but then you should alternatively consider using your shells builtin substitution mechanisms instead of sed). If you're writing a script to manipulate text in general, though, then you should be using awk and so using sed for this part of it wouldn't make any sense. – Ed Morton Feb 23 '17 at 00:06