0

I am a new bash learner. I want to know, how to replace a letter with another in bash. The task is: I have to take some strings from standard input. Then I have to process every string. For one string, I have to replace the first occurrence of capital letter with ..

Say the input is like the following:

Namibia
Nauru
Nepal
Netherlands
NewZealand
Nicaragua
nIgEr
Nigeria
NorthKorea
Norway

The output should be like:

.amibia .auru .epal .etherlands .ewZealand .icaragua n.ger .igeria .orthKorea .orway

As far I could do:

countries=()
while read -r country; do
    # here I have to do something to detect the first occurrence of capital letter and then replace it with a dot(.)
    countries+=( "$country" )
done
echo "${countries[@]}"

Please, help.

Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
  • You might find inspiration [here](http://stackoverflow.com/questions/428109/extract-substring-in-bash). – Jens Jul 02 '15 at 22:41

1 Answers1

2

Replace

countries+=( "$country" )

with

countries+=( "${country/[[:upper:]]/.}" )
bgoldst
  • 34,190
  • 6
  • 38
  • 64
  • Why it does not work if a ``.`` comes in the input? see [here](https://ideone.com/98SkiT) – Enamul Hassan Jul 02 '15 at 22:54
  • 1
    You've run into an annoying quirk that sometimes affects Unix pipelines. The stdin text does not have a line ending on the final line. This is an artifact of the way the ideone.com site handles the text that you input into the stdin text area. They could have designed the site to always ensure that the final input line has a line ending attached to it, but they did not. This causes `read` to not process that final line, because the `read` bash builtin never processes a line until it gets the line ending. This can be fixed by adding it yourself; see https://ideone.com/v9fHW6. – bgoldst Jul 02 '15 at 23:03
  • 1
    To be clear, the issue had nothing to do with a `.` in the input; notice that the third line also has a dot and was processed correctly. The issue was due to the lack of a final line ending as I described above. – bgoldst Jul 02 '15 at 23:06