Skip to content
Advertisement

converting 4 digit year to 2 digit in shell script

I have file as:

$cat file.txt
1981080512 14 15
2019050612 17 18
2020040912 19 95

Here the 1st column represents dates as YYYYMMDDHH

I would like to write the dates as YYMMDDHH. So the desire output is:

81080512 14 15
19050612 17 18
20040912 19 95

My script:

while read -r x;do
yy=$(echo $x | awk '{print substr($0,3,2)}')
mm=$(echo $x | awk '{print substr($0,5,2)}')
dd=$(echo $x | awk '{print substr($0,7,2)}')
hh=$(echo $x | awk '{print substr($0,9,2)}')

awk '{printf "%10s%4s%4sn",'$yy$mm$dd$hh',$2,$3}'
done < file.txt

It is printing

81080512   14  15
81080512   17  18

Any help please. Thank you.

Advertisement

Answer

Please don’t kill me for this simple answer, but what about this:

cut -c 3- file.txt

You simply cut the first two digits by showing character 3 till the end of every line (the -c switch indicates that you need to cut characters (not bytes, …)).

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement