In bash, code like this will read each line in a file one at a time:

while IFS=$'\r' read -r line || [[ -n "$line" ]]; do
done < "to-read-file"

When the code is running, as long as it hasn't reached the final line of the to-read-file, I can add lines to the end of the to-read-file and the code will continue working on new added lines.

I need your help for a similar code in csh. Currently the code I am using under csh is like this:

foreach line (cat to-read-file) 
(do things) 

It will read all the lines at once. Once the code is running, the new lines added to the to-read-file will not be read. Any idea how I can make it read the line once at a time? For some reason I have to work under csh for this case.

Thank you very much.

  • csh doesn't have a read built-in, or anything similar. BTW, assuming you meant foreach line (`cat to-read-file`) (with backticks), the cat is executed only once to construct the list of words for the foreach, it exits as soon as it finishes reading the file. csh has many flaws and is not suitable for scripting - it's not even a good interactive shell (it had some good features for its time when it was first release in 1978, but bourne shells have long since surpassed them). – cas Mar 16 '18 at 1:26
  • btw, the sh read loop will also terminate when it reaches EOF but it's not so obvious because it's reading the file one line at a time. Also BTW, relying on this is introducing a deliberate race-condition to your code - if you want to continuously read a file as it is growing, use tail -f in either a pipe or a process substitution. Finally, if you don't want to switch to a bourne shell, use a language like awk or sed or perl to process your file (I'd recommend this in sh too because while sh is capable of doing this, it's a very slow and inefficient tool for the job). – cas Mar 16 '18 at 1:34
  • @cas thank you very much. As I said I have to deal with csh in this case. Can you instruct me how to use awk or sed or perl as you suggested to read in lines one at a time in a csh script? – michael morgan Mar 16 '18 at 20:31
set v = `cat file`
@ i = 1
while ( $i <= $#v )
    echo $v[$i]
    @ i = $i + 1
  • add line breaks - it removed them – Isaac Kaliski May 15 at 7:25
  • 1
    Welcome on U&L! The box in which you compose questions and answers gives you a fair amount of information on how to format posts, including code. Particularly, please have a look at the question mark icon in the upper right corner of that box. – fra-san May 15 at 7:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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