Transform date format DD/MM/YY into MM/DD/YY into Shell Script

Asked

Viewed 507 times

2

The script reads the date of a . txt in DD/MM/YY format, and I need to convert it to MM/DD/YY format with Bash, Sed or AWK.

3 answers

1


In bash, there is something called "Parameter Expansion" which consists of manipulating the arguments. Knowing this, I recommend that you avoid using sed and/or awk in pipelines. Because, because each pipeline generates a process, this can slow down your code.

Using "Xpansion" can be a bit confusing at first, but it’s a good trick! See:

$ set -- "31/12/1970"
$ echo "${1:3:3}${1:0:3}${1:6:4}"
12/31/1970

The syntax is simple: ${variável:offset:tamanho}. In this case, I left the "31/12/1970" as a parameter $1 and I was formatting each information just taking advantage of each "offset" that is the location of the characters -, already the size, refers to the amount of characters that will be shown from the offset you defined. That is to say:

$ set -- "Edition 3"
$ echo "${1:8:1}rd ${1:0:7}"
3rd Edition

Another tip to make it more readable, you can use as an array. So you have a "reference" of what you are dealing with:

$ set -- "31/12/1970"
$ txt=("${1}")
$ echo "${txt[0]:3:3}${txt[0]:0:2}${txt[0]:5:5}"
12/31/1970

ps: Make sure they are double quotes if you put a syntax like: $variable. It can give you some confusion if this $variavel is empty. Then, to avoid, just use this way: "$variavel".

0

A different way to do it is by using the sed:

echo "31/12/1970" | sed -r 's/(.*)\/(.*)\/(.*)/\2\/\1\/\3/g'

0

I just figured out how.

It is possible to do using AWK as follows:

data=`echo $data | awk -F/ '{ print $2"/"$1"/"$3 }'`

This is very useful to get the difference between two dates.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.