0

I am learning bash scripting and I have this script:

#!/bin/sh
while read line; do
    for word in $line; do
        echo "word = '$word'"
    done
done <"words.txt"

and here are the contents of words.txt

ddddd g
eeee fffffff

Here is the output:

word = 'ddddd'
'ord = 'g
word = 'eeee'
'ord = 'fffffff

What is going on with the output on line 2 and 4? Why is it not print word = 'g' ?

I am using cmder-mini on windows.

thank you.

Priyshrm
  • 662
  • 8
  • 20
  • 5
    Your input file likely is CRLF encoded from windows (so newlines are `\r\n`). While `read line` is going to split out the `\n` parts, when you append `\r` you are really moving the cursor to the start of the string. So you have `word = 'g`, then `\r` takes you to the start, and you finish the output with `'` (overwriting `w`) for a final result of `'ord = 'g`. You only see it every other line because you have two words per line from the input file. – Rogue Mar 20 '23 at 05:41
  • Also `sh != bash` – Jetchisel Mar 20 '23 at 06:18
  • ok, so what needs to be done to fix this? – Priyshrm Mar 20 '23 at 06:46
  • If you have `dos2unix` then run `dos2unix words.txt` before calling your script. Or, `sed -i 's/\r$//' words.txt` if you have GNU `sed`. – M. Nejat Aydin Mar 20 '23 at 07:05
  • Here is a lot of question about this on SO! Question closed with some duplicates pointing to `tr -d \\r`, `dos2unix`and lot of other answers. – F. Hauri - Give Up GitHub Mar 20 '23 at 07:07

0 Answers0