Home > other >  converting 4 digit year to 2 digit in shell script
converting 4 digit year to 2 digit in shell script

Time:10-29

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 "s%4s%4s\n",'$yy$mm$dd$hh',$2,$3}'
done < file.txt

It is printing

81080512   14  15
81080512   17  18

Any help please. Thank you.

CodePudding user response:

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, ...)).

  • Related