Sci-Tech Sci-Tech - 6 months ago 18
Linux Question

Bash: opening file which name in listed inside another file

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

Answer

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.

Comments