Convert months into string to integers?

0

I have an output of one month:

Agosto

I want to convert it to whole:

08

In linux Bash, I have the following code ... But it does not work, since it gives me jumps of the line with each converted element:

com2=$(cut -d/ -f2,2 tmp_date.log | sed -n '1p')
print "$com2" > tmp_date2.log
if [[ "$com2" = "December" ]] then month=12
    elif [[ "$com2" = "November" ]] then month=11
    elif [[ "$com2" = "October" ]] then month=10
    elif [[ "$com2" = "September" ]] then month=09
    elif [[ "$com2" = "August" ]] then month=08
    elif [[ "$com2" = "July" ]] then month=07
    elif [[ "$com2" = "June" ]] then month=06
    elif [[ "$com2" = "May" ]] then month=05
    elif [[ "$com2" = "April" ]] then month=04
    elif [[ "$com2" = "March" ]] then monnth=03
    elif [[ "$com2" = "February" ]] then month=02
    elif [[ "$com2" = "January" ]] then month=01
fi
echo ${month}

There is some other way to make it more efficient.

    
asked by Mareyes 17.10.2018 в 18:59
source

3 answers

0

If you can use sed , even though I'm not an expert, you could create multiple patterns to replace the names with the numbers, something like this:

nombre=Agosto
mes=$(sed 's/Enero/01/g; s/Febrero/02/g; s/Marzo/03/g; s/Abril/04/g; s/Mayo/05/g; s/Junio/06/g; s/Julio/07/g; s/Agosto/08/g; s/Septiembre/09/g; s/Octubre/10/g; s/Noviembre/11/g; s/Diciembre/12/g' <<< $nombre)
echo "$nombre es el mes $mes"

Agosto es el mes 08

Or I recommend an arrays of months, we could get the index:

# El indice comienza en 0 por lo que agregamos un Dummy
meses=(Dummy Enero Febrero Marzo Abril Mayo Junio Julio Agosto Septiembre Octubre Noviembre Diciembre)
nombre=Agosto

for i in "${!meses[@]}"; do
   if [[ "${meses[$i]}" = "${nombre}" ]]; then
       mes=${i};
   fi
done

echo "$nombre es el mes $mes"

Sources: 1 and 2

    
answered by 17.10.2018 / 19:57
source
0

You could use printf instead of echo, that is, something like this:

printf ${month}

With that I think it will work.

Good luck!

    
answered by 17.10.2018 в 19:11
0

Based on your code the line break should be because you do not add the -n flag to the echo command, that is, the final command would have to be:

echo -n ${month}

Now if you have problems with your script you can use the following script:

case ${com2} in
    Enero|January) month=01 ;;
    Febrero|February) month=02 ;;
    Marzo|March) month=03 ;;
    Abril|April) month=04 ;;
    Mayo|May) month=05 ;;
    Junio|June) month=06 ;;
    Julio|July) month=07 ;;
    Agosto|August) month=08 ;;
    Septiembre|September) month=09 ;;
    Octubre|October) month=10 ;;
    Noviembre|November) month=11 ;;
    Diciembre|December) month=12 ;;
esac
echo -n ${month}

With the advantage that you could add new month formats such as Oct, Oct, etc.

    
answered by 17.10.2018 в 20:24