0

I have a file that contains a list of file names to be opened later. After I load lines (file names) to variables, for a reason unknown to me I cannot open it as a file later.

Here is a simplified example of what i'm trying to do:

Main file's contents:

first_file.txt
second_file.txt

Bash commands:

read line < $main_file   # file with the list, received as an argument
echo $line               # to check that correct filename has been read
cat $line                # attempt to dump "first_file.txt" contents <- FAILS
cat first_file.txt       # read "first_file.txt" contents manually 

Execution esult:

first_file.txt
: No such file or directory
*** this is 1st file's contents ***
*** ....

So, cat first_file.txt works, $line contains "first_file.txt", but cat $line fails...

I obviously misunderstand something here, suggestions are welcomed!

Edit: As requested, here is cat -v $main_file's output:

first_file.txt^M
second_file.txt^M
third_file.txt^M
^M
^M
Sci-Tech
  • 3
  • 2
  • 1
    Are there "hidden" characters, like say `\r` at the end of the lines in the source file? Then it would print right, but not work. Can you edit the question with the output of `cat -v main_file`? – Eric Renouf May 22 '16 at 19:31

1 Answers1

1

The ^M characters are carriage returns (a.k.a. \r) and are often part of a Windows line ending. They don't show up when you echo them, but they are messing up your ability to open a file with the text having it at the end.

The best solution is to remove them from your "main file." You could use the dos2unix tool if you have it, or you could use GNU sed like sed -i -e 's/\s+$//g' $main_file to edit it in place and remove the extra white space (which includes ^M) from the end of each line.

Eric Renouf
  • 13,950
  • 3
  • 45
  • 67
  • You are correct. I stripped leading and trailing white-spaces from the variable using: `line="$(echo -e "${line}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"` command, as proposed [here](https://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-a-bash-variable). And now it works! Thanks! – Sci-Tech May 22 '16 at 19:59