Bash脚本正则表达式…如何查找和替换所有匹配项?

问题描述 投票:11回答:4

我正在编写一个bash脚本,该脚本逐行读取文件。

该文件是.csv文件,其中包含许多日期,格式为DD / MM / YYYY,但我想将它们更改为YYYY-MM-DD。

我将使用正则表达式匹配数据,并进行替换,以使文件中的所有日期都正确地格式化为YYYY-MM-DD。

我相信此正则表达式将与日期匹配:

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

但是我不知道如何找到正则表达式匹配项,并用新格式替换它们,或者即使在bash脚本中也可以做到这一点。请帮助!

regex bash shell search replace
4个回答
23
投票

尝试使用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:在Mac上,使用sed -E代替sed -r


16
投票

纯重击。

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"

输入文件

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

提供以下输出:

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

2
投票

您可以使用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/'

0
投票

我不想回声...我想将结果存储在新变量中

为此(我知道这并不适合您的设置,但仍然适用于如何使用正则表达式):

path="/entertainment/Pictures"
files=(
  "$path"/*.jpg"
  "$path"/*.bmp"
)

for i in "${files[@]}"
do
  # replace jpg and bmp with png in prep for conversion
  new=$(echo "$i" | perl -pe "s/\.jpg|\.bmp/.png")

  # next is to perform the conversion
  ...
done
© www.soinside.com 2019 - 2024. All rights reserved.