0

I have a text file as follows:

2018 11 20
2018 11 21
2018 11 22
2018 11 23
2018 11 24
2018 11 25
2018 11 26
2018 11 27

This file consists of year,month and day with three columns. I need to add hyphen - between the year, month and day as follows:

2018-11-20
2018-11-21
2018-11-22
2018-11-23
2018-11-24
2018-11-25
2018-11-26
2018-11-27
Zanna
  • 72,312
deepblue_86
  • 1,246

1 Answers1

3

sed

Assuming there's no spaces after the last column, we can do

sed 's/[[:blank:]]/-/g' input.txt

In case where there may be other characters and we specifically want to capture the pattern "sequence of digits, then sequence of spaces" we can also use group patterns in parenthesis and extended regex -r:

sed -r 's/([[:digit:]]?+) ?+([[:digit:]]?+) ?+([[:digit:]]?+)/\1-\2-\3/' input.txt

shell

In case we want shell-only solution:

while read -r year month day trash; do
    printf "%s-%s-%s\n" "$year" "$month" "$day"
done < input.txt
dessert
  • 40,956