[英]How to use a number stored in a variable in an awk command
I am attempting to have the script grab a random record from a file. 我试图让脚本从文件中获取随机记录。 The file has 10 total records. 该文件共有10条记录。 Not sure why what I currently have is not working. 不知道为什么我目前无法使用。 (I have ``around what n is equal to) (我有``大约等于n)
n=expr $RANDOM % 10 + 1
awk 'BEGIN{RS = "%"} NR==$n' pathToFile
If I substitute $n
for any number 1-10
there are no issues. 如果我用$n
代替任何1-10
数字,就没有问题。
You can generate the random number within awk
to avoid quoting challenges: 您可以在awk
内生成随机数以避免引用挑战:
awk -v min=1 -v max=10 'BEGIN{srand()
n=int(min+rand()*(max-min+1))
}
#... the rest of the awk ...'
If you want to print a random record: 如果要打印随机记录:
awk -v min=1 -v max=10 'BEGIN{srand()
n=int(min+rand()*(max-min+1))
}
NR==n {print; exit}' file
Or, you can generate and assign on the awk
command line: 或者,您可以在awk
命令行上生成和分配:
$ awk -v n=$(expr $RANDOM % 10 + 1) 'BEGIN{ print n }'
Or, 要么,
$ echo $n
7
$ awk -v n="$n" 'BEGIN{ print n }'
7
This should work the way you want: 这应该按照您想要的方式工作:
awk 'BEGIN{RS = "%"} NR=="'"$n"'"' /folder/file
Note that the only difference from your code is the extra "'" "'"
around the variable. 请注意,与您的代码唯一的区别是变量周围有多余的"'" "'"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.