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
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
Try this 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
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
You can do it 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/'