conor.ob
conor.ob

Reputation: 97

AWK NR Variable Syntax Issue

I am new to AWK and trying to write some code where I can delete all files in a directory apart from the newest N number. My code works if I use a hard coded number instead of a variable. Works:

delete=`ls -t | awk 'NR>3'`
echo $delete

Does Not Work:

 amount=3
 delete=`ls -t | awk 'NR>$amount'`
 echo $delete 

I know the problem lies somewhere with the bash variable not being recognised as an awk variable however I do not know how to correct. I have tried variations of code to fix this such as below, however I am still at a loss.

amount=3
delete=`ls -t | awk -v VAR=${amount} 'NR>VAR'`
echo $delete

Could you please advise what the correct code is ?

Upvotes: 2

Views: 632

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754190

Shells don't expand anything inside single quotes.

Either:

amount=3
delete=$(ls -t | awk "NR>$amount")

or:

amount=3
delete=$(ls -t | awk -v amount=$amount 'NR > amount')

Be aware that parsing the output of ls is fraught if your file names are not limited to the portable file name character set. Spaces, newlines, and other special characters in the file name can wreck the parsing.

Upvotes: 4

tripleee
tripleee

Reputation: 189527

The simplest fix is to use double quotes instead of single. Single quotes prevent the shell from interpolating the variable $amount in the quoted string.

amount=3
ls -t | awk "NR>$amount"

I would not use a variable to capture the result. If you do use one, you need to quote it properly when interpolating it.

amount=3
delete=$(ls -t | awk -v VAR="$amount" 'NR>VAR')
echo "$delete"

Note that this is basically identical to your second attempt, which should have worked, modulo the string quoting issues.

Upvotes: 1

Related Questions