Text manipulation with sed/awk in a bash script

Guys, I have a variable in a script that I want to transform to into something else Im hoping you guys can help. It doesn't have to use sed/awk but I figured these would be the simplest.

DATE=20160120

I'd like to transform $DATE into "01-20-16" and move it into a new variable called $SIMPLEDATE

the format is always the same, notice I need to transform 2016 in just 16 and move it around.

thanks

Any attempts/ideas/thoughts from your side?

Easy

DATE=20160120; echo $DATE | sed 's/[0-9]/& /g' | tr 0-9 a-k | 
awk '{print $5, $6, $7, $8, $3, $4}' | sed 's/ //g' |
sed 's/./&-/2; s/./&-/5' | tr a-k 0-9

Anyhow, try

date -d$DATE +%d-%m-%y
20-01-16
echo ${DATE:6:2}-${DATE:4:2}-${DATE:2:2}
20-01-16

What about AIX, HP, Solaris - they do not have -d option for date.

No. My version is the right. :stuck_out_tongue:

DATE=20160120
SIMPLEDATE=`echo "$DATE" | sed 's/..\(..\)\(..\)\(..\)/\2-\3-\1/'`
echo "$SIMPLEDATE"
01-20-16
1 Like

This is perfect man, thank you...
Can you explain exactly whats going on here? I read some info on sed but to be honest Im not following. I'd love to learn so I can do this myself next time.

The sed code starts with s , the substitute command.
The following character / is a delimiter, followed by a Regular Expresson, a delimiter, and the substitution string. The substitution string is terminated by another delimiter (that can be followed by an option).
In a Regular Expression each . matches a character.
By a \( \) one can mark groups.
The first group contains the 3rd and 4th character, the second group contains the 5th and 6th character, ...
The reference to the first group is \1
The second group should be printed first, so the \2 is first in the substitution string. Followed by a - , followed by the third group, ...

1 Like

Great explain, thanks alot.