Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write foreach in one line in csh?

Tags:

shell

foreach

csh

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?

like image 785
Chan Kim Avatar asked Sep 12 '14 12:09

Chan Kim


People also ask

What does $? Mean in CSH?

$? -The exit status of the last command executed. $0 -The filename of the current script. $# -The number of arguments supplied to a script.

How do you set a variable in TCSH?

You use the set or setenv commands to initialize a variable, where set is used for current shell and setenv for current and any subshells (i.e. it will automatically export variables to subshell). setenv should be used for PATH, HOME, and all other system related environmental settings.


2 Answers

This method works for me:

printf 'foreach f ( 1 2 3 )\n echo $f \n end' | tcsh
like image 86
Jonathan Gratus Avatar answered Sep 21 '22 07:09

Jonathan Gratus


There is no easy way to do the foreach in one line under tcsh.

However, by using alias, you may get something very close to your question.

alias disp 'foreach i (*.txt)\
  cat $i\
end'

You can call disp in your terminal.

If you want to direct the result into a pipe, then echo `disp` | grep foobar.

Sometimes, we need to save the result first, before further processing: set foo=`disp`

like image 2
TerrenceSun Avatar answered Sep 23 '22 07:09

TerrenceSun