Ask your questions here.
Post a reply
nadir

- nadir
- Posts: 1160
- Joined: Wed Mar 09, 2011 4:18 am
- Location: here

## grep awk head ...

Tue Dec 04, 2012 10:55 pm

I am a bit proud of the stuff to follow,
but i also ask for a better solution
(or something like: well, it's ok and does the job is good too).
In plain words this is the problem.
During the same day i usually train the same problems of C programming.
That means that the head (?), that is: anything above the line
int main(int argc, char *argv[])
is the same (includes, defines, function prototypes, structures and what else).
So, if i edit the next file, i would try to avoid to have type all of that again.
I just want to copy the "head" (anything above the line with "int main(int argc, char *argv[])) to the new file.
The most easy solution, the one i have searched for, would be if
- grep had a switch to _only_ print the line in which the pattern is found
- use that for "head -n <result of grep >
And i would be done.
But grep doesn't seem to contain such a switch.
So, what i figured out is this:

Code:
  `head -n $(grep -n main hello-world.c | awk -F: '{print $1}') hello-world.c
  `

- grep -n main hello-world will give me such output:
16:int main(int argc, char *argv[])
- piping that to awk will give me the line number only:
grep -n main hello-world.c | awk -F: '{print $1}'
16
- and the whole above put into $() will be passed to head -n $(voodoo-piping)
and i get my result.
The awk command i found in some refracta scripts, grep i had to search the Web and head seems clear.
I asked the same at forums debian, btw.
Thanks for corrections, ideas, input, proposals etc.
(ok: copy and paste with the mouse is an idea .... )
fsmithred

- fsmithred
- Posts: 2101
- Joined: Wed Mar 09, 2011 9:13 pm

## Re: grep awk head ...

Wed Dec 05, 2012 4:29 am

Looks good. Took me a few minutes to figure out what you're doing. For fun, here's another way (I think.) This is a modified version of a script you wrote.

Code:
  `#!/usr/bin/env bash
  # read lines of one file into another until pattern is found
  infile="$1"
  outfile="$2"
  while read -r line
  do
  echo "$line" >> "$outfile"
  if [[ $line =~ pattern ]];then
  exit 0
  fi
  done < "$infile"
  exit 0`

nadir

- nadir
- Posts: 1160
- Joined: Wed Mar 09, 2011 4:18 am
- Location: here

## Re: grep awk head ...

Wed Dec 05, 2012 7:13 pm

Oh, that is a good one.
read is tough, but the script is good.
thanks.
Post a reply
Jump to:

Powered by phpBB © phpBB Group.

phpBB Mobile / SEO by Artodia.