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

2

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

    
asked by anonymous 14.10.2016 / 00:12

3 answers

1

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

Using "parameter expansion" 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 "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 set. That is:

$ 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-quoted, if you put a syntax of type: $ variable. It may give you some confusion if this $variavel is empty. So to avoid, just use this way: "$ variable".

    
28.01.2017 / 04:05
0

I just found out how.

You can do this using AWK as follows:

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

This is very useful for getting the difference between two dates.

    
14.10.2016 / 00:22
0

A different way to do it is to use sed :

echo "31/12/1970" | sed -r 's/(.*)\/(.*)\/(.*)/\/\//g'
    
01.12.2016 / 13:48