Sed/Awk: print lines between n'th and (n+1)'th match of "foo"
I have a textfile, which may for example look like this:
Code:
blaaat The user enters a number (call it $1), my script should use sed and/or awk to print out the x-th record in the file. This is what I've got so far, it's only input-checking actually: Code:
ubound=`cat $file | grep -c -e -o-` |
awk -v RS='-o-' 'NR == '$1' { print }' input_file
|
Quote:
Code:
ubound=$(grep -c '^-o-$' $file) |
Quote:
edit2: I hadn't noticed the double [[/]] you used there... do they have the same effect? edit: Why should I prefer your way of setting ubound above mine? (no offense ;) ) I agree it looks better, but are there other advantages? I never actually learned about the $( )-construction, so... |
Also, the solution you first advised does not seem to work correctly, here's a bash-session:
Code:
Macbook-2:~/ex_st xaverius$ cat getMessage |
Hi,
I just tried (copy->paste) the test session in your previous post (#5), and it works. I did notice something else: Your prompt says: Macbook-2. Are you trying this on Apple's OS X? If so, check to see which awk is actually used and if it is posix compliant. Maybe you can use nawk instead. Hope this helps. |
I have no idea which version of awk OSX is using, but I had access to another machine:
Code:
$ uname -a Thx! Btw: still interested in a way to solve it using sed though :p |
Quote:
Quote:
Code:
if [[ ! $1 =~ ^[0-9]+$ || $1 -lt 1 || $1 -gt $ubound ]]; then Quote:
Quote:
|
Quote:
Code:
# var=1 |
Quote:
Code:
awk -v RS='-o-' 'NR == '$1' { print }' input_file Code:
:cat foo.sh |
Quote:
Code:
# more file |
So give $1 a value by passing in an argument.
|
Quote:
|
Ah, yeah, that's easy to do. One of the most bothersome things about mixing shell and awk.
|
This is what the final script looks like:
Code:
#!/bin/bash It's tested on GNU awk 3.0.4 Can someone explain the awk rule please? If the current record = $1, then print this line - but what is the value of $1? Is it supposed to be the bash $1, or the awk $1? It's not really clear to me... The -v flag is used to set the recordseperator (RS) I guess... |
All times are GMT -5. The time now is 03:28 PM. |