views:

63

answers:

7

Assuming:

  1. the path of file f is ~/f
  2. "which f" shows "~/f",

Then,

which f | cat shows ~/f. So cat here is applied to the quotation of ~/f, which is different with cat ~/f.

My question is: how I could use one command composed of which and cat to achieve the result of cat ~/f? When I don't know the result of which f in advance, using this composition can be very convenient. Currently, if I don't know the result of which f in advance, I have to invoke which f first, and copy-paste the result to feed less.

A related question is: how can I assign the result of which f to a variable?

Thanks a lot!

A: 

Like so in bash:

cat "$(which f)"
var="$(which f)"
Ignacio Vazquez-Abrams
+1  A: 

cat "`which f`"

asveikau
A: 

What you want is:

cat `which f`
slebetman
+2  A: 

Try:

cat `which ~/f`

For the related question:

foo=`which ~/f`
echo $foo
Eli
A: 

In bash, you can use:

cat "$(which f)"

to output the contents of the f that which finds. This, like the backtick solution, takes the output of the command within $(...) and uses that as a parameter to the cat command.

I prefer the $(...) to the backtick method since the former can be nested in more complex situations.

Assigning the output of which to a variable is done similarly:

full_f="$(which f)"

In both cases, it's better to use the quotes in case f, or it's path, contains spaces, as heinous as that crime is :-)

I've often used a similar trick when I want to edit a small group of files with similar names under a given sub-directory:

vim $(find . -type f -name Makefile)

which will give me a single vim session for all the makefiles (obviously, if there were a large number, I'd be using sed or perl to modify them en masse instead of vim).

paxdiablo
A: 

In which f | cat the cat program gets the output of which f on standard input. That then just passes that standard input through, so the result is the same as a plain which f. In the call cat ~/f the data is passed as a parameter to the command. cat then opens the file ~/f and displays it's contents.

To get the output of which f as a parameter to cat you can, as others have answered, use backticks or $():

cat `which f`
cat $(which f)

Here the shell takes the output of which f and inserts it as a parameter for cat.

sth
A: 

cat echos the contents of files to the standard output. When you write stuff | cat, the file cat works on is the standard input, which is connected to the output of stuff (because pipes are files, just like nearly everything else in unix).

There is no quoting going on in the sense that a lisp programmer would use the word.

dmckee
Yeah, indeed I was thinking about Lisp :-)
PainterZ