Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace hyphen with space using bash

Tags:

regex

bash

sed

I'm reading a filename that has this data:

2017-03-23
2018-01-23
2017-07-31

I want to read each line and replace the hyphens with spaces. Given the above example, I should get the following:

2017 03 23
2018 01 23
2017 07 31

Here's my code:

#!/bin/sh

filename=extract_dates.dat
line=1
totline=`wc -l < $filename`

while [ $line -le $totline ]
do
    date=`sed -n -e ''"$line"'p' $filename | awk '{print $line}'`
    echo $date
    test=`sed 's/([0-9])-([0-9])/\1\2/g' $date`
    echo $test
    line=`expr $line + 1`
done

I get the following error:

sed: 1: "s/([0-9])-([0-9])/\1\2/g": \1 not defined in the RE
like image 923
aloha Avatar asked Aug 28 '26 18:08

aloha


1 Answers

tr will replace hyphens with spaces, for example:

test=$(echo $date | tr "-" " ")
like image 96
aloha Avatar answered Aug 30 '26 21:08

aloha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!