LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   csh: while read (https://www.linuxquestions.org/questions/programming-9/csh-while-read-738708/)

eantoranz 07-08-2009 03:34 PM

csh: while read
 
Is there an equivalent in csh to bash's while read variable list?

Uncle_Theodore 07-08-2009 04:17 PM

AFAIK, the answer is no.

eantoranz 07-08-2009 04:31 PM

Well, I had to do it with a rather long trick:

say, in bash:

Code:

cat /etc/passwd | while read blah; do
    echo $blah
done

in csh:
Code:

set lines=`cat /etc/passwd`
set i=1
while ( $i <= $#lines )
    echo $lines[$i]
    @ i = $i + 1
end

Or something like that

colucix 07-08-2009 04:38 PM

Or something like:
Code:

foreach line ( "`cat /etc/passwd`" )
  echo $line
end


eantoranz 07-08-2009 04:43 PM

That's right, but in my case I had two variables to get from every line, so I couldn't use the foreach and had to go with the while instead.

colucix 07-08-2009 05:17 PM

In C-shell it's not possible to read multiple variables, but you can do a trick like this:
Code:

foreach line ( "`cat file`" )
  set argv = ( $line )
  set name1 = $1
  set name2 = $2
  echo $name1
  echo $name2
end

or eventually use the cut command to split the line into fields, using a custom field separator as : (colon) to parse /etc/passwd.

colucix 07-08-2009 05:48 PM

This should work for /etc/passwd:
Code:

foreach line ( "`cat /etc/passwd`" )
  set line = "$line:gas/ /_/"
  set line = "$line:gas/:/ /"
  set argv = ( $line )
  set name1 = $1
  set name2 = "$5:gas/_/ /"
  echo $name2
end

It uses variable modifiers. It replace any blank space with _ (underscore), then any : with a blank space. Finally it extracts the fields, replacing _ with a blank space in those fields where a blank space can appear (needed only for those fields where a blank space can actually appear, like the fifth field).


All times are GMT -5. The time now is 06:45 PM.