bash脚本定期防爆pressions ...如何查找和替换所有的匹配? [英] Bash Script Regular Expressions...How to find and replace all matches?
问题描述
我写一个bash脚本,逐行读取一个文件行。
I am writing a bash script that reads a file line by line.
该文件是一个包含格式DD / MM / YYYY许多日期的.csv文件,但我想将其更改为YYYY-MM-DD。
The file is a .csv file which contains many dates in the format DD/MM/YYYY but I would like to change them to YYYY-MM-DD.
我会使用常规的前pression相匹配的数据,并更换它使得所有文件中的日期正确格式为YYYY-MM-DD。
I would to match the data using a regular expression, and replace it such that all of the dates in the file are correctly formatted as YYYY-MM-DD.
我相信这个普通的前pression将匹配日期:
I believe this regular expression would match the dates:
([0-9][0-9]?)/([0-9][0-9]?)/([0-9][0-9][0-9][0-9])
但我不知道如何找到正则表达式匹配,并使用新的格式取代他们,或者如果这甚至有可能在bash脚本。请帮助!
But I do not know how to find regex matches and replace them with the new format, or if this is even possible in a bash script. Please help!
推荐答案
试试这个使用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
这篇关于bash脚本定期防爆pressions ...如何查找和替换所有的匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!