how to write foreach in one line in csh?

Chan Kim picture Chan Kim · Sep 12, 2014 · Viewed 18.7k times · Source

Sometimes I use same foreach operation with different target files in csh.
If I can give foreach command in a single line, I could easily substitue the target file names to repeat the process.(I usually use `find . -name ...` for target files)
For the purpose of this question, let's assume I want to cat all the *.txt files.

$ foreach i (*.txt)
foreach? cat $i
foreach? end

I read https://unix.stackexchange.com/questions/32873/running-a-full-foreach-command and tried

alias disp 'echo "foreach i (*.txt)"; echo "cat "\$"i"; echo "end"; | /bin/csh'

when I type disp it gives me Invalid null command.
If I can do it in a single line, I could do !foreach:gs/\.c\>/.h/ (do the same replacing .c with .h). How can I do it?

Answer

Jonathan Gratus picture Jonathan Gratus · Aug 14, 2018

This method works for me:

printf 'foreach f ( 1 2 3 )\n echo $f \n end' | tcsh