Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Greetings,

I'm writing a simple bash script that needs to parse the contents of a file into an array. Entries in the file are "newline" delimited -- so the file would look something like this:

path/to/file
path/to/other/file

I'd like to parse in the contents and iterate over them. My code currently looks like:

CONTENT=`cat /path/to/text/file.txt`
for PATH in $CONTENT
do
   echo $PATH
   chmod -R 440 $PATH
fi

This code works great with a file with UNIX line-endings. With a windows formatted text file, however, it chokes miserably. The "echo $PATH" statement produces the correct path, but the chmod fails saying that the file doesn't exist. My knack is that the Windows line-endings aren't getting trimmed, so its trying to chmod a file-path that includes a new line character.

I need to make this thing work regardless of whether the target file was created with Unix or Windows newlines -- but given I am somewhat new to shell scripting I'm not all that sure how to do it.

I appreciate your help!

share|improve this question
add comment

2 Answers 2

up vote 5 down vote accepted

Sounds like you just need to remove the carriage return when processing each line. The real easy way is to use the dos2unix utility, but if your system doesn't have that or you can't get it, you can accomplish similar things with tr, e.g:

echo $PATH | tr -d '\r'

More ideas, such as using sed, are available on the Wikipedia entry.

EDIT: I should point out that $PATH is not a great variable name, since it is undoubtedly set by the environment and other programs may depend on its value. You should consider changing it to something like $CUR_PATH.

share|improve this answer
    
Pwnage. Thanks man. –  Skone Jan 26 '10 at 0:46
    
@Skone: no problemo –  bjlaub Jan 26 '10 at 0:49
add comment

I'd just change the first line of the script:

CONTENT=$(tr -d \\r < /path/to/text/file.txt)

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.