Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 尝试从用户输入对列进行排序_Bash_Unix_Scripting - Fatal编程技术网

Bash 尝试从用户输入对列进行排序

Bash 尝试从用户输入对列进行排序,bash,unix,scripting,Bash,Unix,Scripting,因此,我试图从一组文件中的特定列中找到最小值和最大值,然后将这些值放入两个文本文件中。我希望脚本排序的列是用户输入的数字。这是我的代码,它在大多数情况下都有效,只是它给了我每列的最小值和最大值。我该如何解决这个问题 echo "Please enter a column you wish to change: " read userinput if [ ${userinput} -gt 10 ]; then echo "Error" else sort -nk${user

因此,我试图从一组文件中的特定列中找到最小值和最大值,然后将这些值放入两个文本文件中。我希望脚本排序的列是用户输入的数字。这是我的代码,它在大多数情况下都有效,只是它给了我每列的最小值和最大值。我该如何解决这个问题

echo "Please enter a column you wish to change: "
read userinput
if [ ${userinput} -gt 10 ]; then
      echo "Error"
else
      sort -nk${userinput} Node{1..4}.txt | awk 'NR==1{print $userinput}' > result.txt
      sort -nk${userinput} Node{1..4}.txt | awk 'END{print $userinput}' > results.txt
fi

排序部分中的${userinput}应该是用户指定的列,因此,例如,如果用户输入“10”,那么它将是sort-nk10。该脚本在大部分情况下都有效,除了在检查我指定的所有四个文本文件时,它为我提供了所有列的最小值和最大值。如何修复它,使其仅提供用户指定的列的最小值和最大值?

您无法在awk中读取shell变量的值。Uste设置awk变量的
-v
选项

userinput=4
# This will not work
awk 'BEGIN {print "UserInput=" $userinput}'
# This works
awk -v colnr=$userinput 'BEGIN {print "UserInput=" colnr }'
你可以这样使用它

echo "A B C D E F" | awk -v colnr=$userinput '{print "Col " colnr "=" $colnr }'

当我这样做时,result.txt和results.txt文件只给我用户输入的值(因此,如果用户输入数字3,那么这些文件中只包含数字3)添加了示例行
A B C D E F
我现在明白了,谢谢!它就像我所需要的那样工作!