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

后端 未结 4 710
终归单人心
终归单人心 2021-01-17 14:40

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

The file is a .csv file which contains many dates in the format DD/MM/YYYY but I would like to change the

4条回答
  •  时光说笑
    2021-01-17 15:03

    Pure 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"
    

    The 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 output:

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

提交回复
热议问题