views:

165

answers:

3

Hello! I have this set of piped commands:

grep -n '*' file.txt | head -n1 | awk -F\: '{print $1-1;}'

It tells me the previous line to that where it first find asterisks. Now I want to get the previous lines piping that to:

head -n<that previous line number>

Head requires a number following immediately the -n argument, without spaces, for example:

head -n4

How can I do that? It just won't accept adding

| head -n

at the end of the set of commands. My searches have been fruitless. Thanks!

+4  A: 

You want back-ticks to substitute the value:

head -n`grep -n '*' file.txt | head -n1 | awk -F\: '{print $1-1;}'` file.txt

Or possibly something similar on multiple lines:

LINENO=`grep -n '*' file.txt | head -n1 | awk -F\: '{print $1-1;}'`
head -n${LINENO} file.txt
Douglas Leeder
Excellent! Thanks a lot for your prompt answer!!
David
I suggest to use $() instead of backticks; $() nests and is easier to distinguish than the three types of single quotes which you can find on your keyboard.
Aaron Digulla
+1  A: 

I think you could also use xargs. Something like:

grep -n '*' file.txt | head -n1 | awk -F\: '{print $1-1;}' | xargs -I % head -n% file.txt
Joe Beda
+2  A: 

Why don't you just do:

awk -- '{if (!/*/) print $0; else exit}' file.txt

or this, which is faster:

awk -- '/*/ {exit}; {print}' file.txt
Dennis Williamson
That's an excellent idea, I will better use this, thanks!However, for the sake of consistency with the posed question, I will keep accepting the first answer by Douglas and Aaron as the valid ones. (Joe's answer also works). Sadly, I still can't rate answers!
David