Bash Script Regular Expressions ... How to find and replace all matches?

I am writing a bash script that reads a file line by line.

The file is a CSV file that contains many dates in DD / MM / YYYY format, but I would like to change them to YYYY-MM-DD.

I would like to match the data using a regular expression and replace it so that all dates in the file are correctly formatted as YYYY-MM-DD.

I believe this regex will match dates:

([0-9][0-9]?)/([0-9][0-9]?)/([0-9][0-9][0-9][0-9]) 

But I do not know how to find regular expressions and replace them with a new format, or if it is possible even in a bash script. Please, help!

+8
bash regex shell replace search
Apr 14 2018-11-11T00:
source share
3 answers

Try using sed:

 line='Today is 10/12/2010 and yesterday was 9/11/2010' echo "$line" | sed -r 's#([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})#\3-\2-\1#g' OUTPUT: Today is 2010-12-10 and yesterday was 2010-11-9 

PS: On mac, use sed -E instead of sed -r

+21
Apr 14 2018-11-11T00:
source share

Clean Bash.

 infile='data.csv' while read line ; do if [[ $line =~ ^(.*),([0-9]{1,2})/([0-9]{1,2})/([0-9]{4}),(.*)$ ]] ; then echo "${BASH_REMATCH[1]},${BASH_REMATCH[4]}-${BASH_REMATCH[3]}-${BASH_REMATCH[2]},${BASH_REMATCH[5]}" else echo "$line" fi done < "$infile" 

Input file

 xxxxxxxxx,11/03/2011,yyyyyyyyyyyyy xxxxxxxxx,10/04/2011,yyyyyyyyyyyyy xxxxxxxxx,10/05/2012,yyyyyyyyyyyyy xxxxxxxxx,10/06/2011,yyyyyyyyyyyyy 

gives the following result:

 xxxxxxxxx,2011-03-11,yyyyyyyyyyyyy xxxxxxxxx,2011-04-10,yyyyyyyyyyyyy xxxxxxxxx,2012-05-10,yyyyyyyyyyyyy xxxxxxxxx,2011-06-10,yyyyyyyyyyyyy 
+16
Apr 14 2018-11-11T00:
source share

You can do this using sed

 echo "11/12/2011" | sed -E 's/([0-9][0-9]?)\/([0-9][0-9]?)\/([0-9][0-9][0-9][0-9])/\3-\2-\1/' 
+2
Apr 14 '11 at 3:13
source share



All Articles