Reputation: 4774
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
Upvotes: 6
Views: 8211
Reputation: 384
We can use string replacement of bash instead
#!/bin/bash
input="2017-03-23
2018-01-23
2017-07-31"
output="${input//-/ }"
echo "$output"
Outputs
2017 03 23
2018 01 23
2017 07 31
Upvotes: 2
Reputation: 4774
tr will replace hyphens with spaces, for example:
test=$(echo $date | tr "-" " ")
Upvotes: 12
Reputation: 35405
How about this:
tr '-' ' ' < filename > output
If you want to use sed
, you could use that as well. The reason your sed
command doesn't work is that you need to escape your paranthesis. Try this:
sed 's/\([0-9]\)-\([0-9]\)/\1\2/g' $date
Upvotes: 0
Reputation: 531075
You don't need explicit counters or sed
or awk
; bash
itself can handle this. (Your use of awk
, especially, doesn't really do anything.)
filename=extract_dates.dat
while IFS=- read -r year month day; do
echo "Year: $year"
echo "Month: $month"
echo "Day: $day"
done < "$filename"
Upvotes: 2