I am writing a simple script in tcsh (apparently that's a bad idea, but well) to grep some patterns from a text file. Say we have a file animal_names.txt which consists of:

dog carrot
dog bolt
cat larry
cat brownies
bird parry
bird pirate

and I wrote the script:

set animals = "dog\|cat"
set names = `grep $animals animal_names.txt`
echo "$names"

The intention was to grep all lines with "dog" or "cat". However, the output I get is just oneline:

dog carrot dog bolt cat larry cat brownies

Somehow the newlines were removed at the output. Is there a way to keep the newlines? Another post suggested to use the :q modifier, but it doesn't work in my case.

  • 1
    Can't you just not use tcsh? You can run sh scripts from within a tcsh shell session so there's no reason to use tcsh for scripting. As you point out, (t)csh is just a bad scripting tool.
    – terdon
    Dec 17, 2021 at 9:45
  • maybe related: unix.stackexchange.com/questions/532984/…
    – user271585
    Dec 17, 2021 at 10:00

1 Answer 1


"the output I get is just one line" - unfortunately you've just hit one of the reasons why scripting in [t]csh is problematic. Keeping newlines is either not possible or non-trivial. Use bash (or sh) instead.

Assume this is written to the file find_animals:

names=$(grep -E "$animals" animal_names.txt)
echo "$names"

Notice I've not escaped the RE | symbol but instead told grep to use Extended Regular Expressions (ERE). You could leave it as per your original but I think it's easier to read this way.

Make the script executable

chmod a+x find_animals

Run it in the directory where your animal_names.txt file can be found



dog carrot
dog bolt
cat larry
cat brownies

If you insist on using tcsh this will work:

#!/usr/bin/tcsh -f
set animals = 'dog|cat'
set temp = "`grep -E '$animals' animal_names.txt`"
set names = ""
set nl = '\
foreach i ( $temp:q )
    set names = $names:q$i:r:q$nl:q
set names = $names:r:q
echo $names:q


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .