2

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.

Hanz
  • 33
  • 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 '21 at 09:45
  • maybe related: https://unix.stackexchange.com/questions/532984/how-to-make-tcsh-multiline-prompt-use-newline-character –  Dec 17 '21 at 10:00

1 Answers1

5

"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:

#!/bin/sh
animals='dog|cat'
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

./find_animals

Output

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
end
set names = $names:r:q
echo $names:q

References

Chris Davies
  • 116,213
  • 16
  • 160
  • 287