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 Answers2

3

$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.

choroba
  • 47,233
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"
}
fd0
  • 11