1

I'm trying to add an alias in .bashrc file as follows:

...
alias cutf="_cutf"
...
_cutf() {
   awk 'NR >= $2 && NR <= $3 { print }' < $1
}

(The function's goal is to show the content of the lines whose number is between $2 and $3 for the $1 file)

When I call cutf in a new bash session I get no output.

Am I missing something?

2

$2 and $3 are in single quotes. Shell doesn't expand variables in single quotes, so they get interpreted by awk. Switch to double quotes:

awk "NR >= $2 && NR <= $3 { print }" < "$1"

Note that you can achieve the same with

sed -n 'X,Yp' file

where X and Y are the line numbers, or similarly in Perl with

perl -ne 'print if X .. Y' file

which are both so short you probably don't need a function for them.

| improve this answer | |
1

You should not let the shell expand variables within your awk statement. Variables such as $2 and $3 have a special meaning within awk.

_cutf() {
   awk -v start="$2" -v stop="$3" 'NR >= start && NR <= stop { print }' "$1"
}

or you could write it like this

_cutf() {
   awk 'NR >= start && NR <= stop { print }' start="$2" stop="$3" "$1"
}
| improve this answer | |
  • Does the start and stop parameters make awk more efficient -in my case-? – Diego Nemo Mar 9 '15 at 14:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.