[英]Bash Script Regular Expressions...How to find and replace all matches?
I am writing a bash script that reads a file line by line.我正在编写一个逐行读取文件的 bash 脚本。
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.该文件是一个 .csv 文件,其中包含许多格式为 DD/MM/YYYY 的日期,但我想将它们更改为 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.我会使用正则表达式匹配数据,并替换它,以便文件中的所有日期都正确格式化为 YYYY-MM-DD。
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])
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.但我不知道如何找到正则表达式匹配项并用新格式替换它们,或者这在 bash 脚本中是否可行。 Please help!
请帮忙!
Try this using sed:使用 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
PS:在 mac 上使用
sed -E
而不是sed -r
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
你可以使用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/'
I don't wanna echo...I want to store the result in a new variable我不想回声...我想将结果存储在一个新变量中
to do that (and i know this isn't exacting to your setup, but still applies in how to use a regex):这样做(我知道这对您的设置并不严格,但仍然适用于如何使用正则表达式):
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.