如何在带有变量的 bash 脚本中使用“head”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25042664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use 'head' in a bash script with a variable?
提问by user3892426
I've been trying to create a script that can read a certain line off of a file given some variables I've created.
我一直在尝试创建一个脚本,该脚本可以根据我创建的一些变量从文件中读取特定行。
SCRIPTNUM=$(tail -1 leet.txt)
LINE=$(echo $SCRIPTNUM | python leetSolver.py)
PART1=$(head "-$LINE" leet.txt)
FLAG=$(printf "$PART1" | tail -1)
FLAGFORMAT="$FLAG\n"
printf $FLAGFORMAT
From this the biggest problem I face is that I get this error:
由此我面临的最大问题是我收到此错误:
head: invalid trailing option --
Try `head --help' for more information.
The code works just fine when inputted through the terminal one line at a time. Is there a way to make this code work? It's worth noting that using a constant (ie head -5) works.
当通过终端一次一行输入时,代码工作得很好。有没有办法让这段代码工作?值得注意的是,使用常量(即 head -5)是有效的。
采纳答案by Etan Reisner
A quick test here seems to indicate that the problem is that your $LINE
variable has trailing spaces (i.e. '5 '
instead of '5'
).
Try removing them.
这里的快速测试似乎表明问题在于您的$LINE
变量有尾随空格(即'5 '
代替'5'
)。尝试删除它们。
$ head '-5g' file
head: invalid trailing option -- g
Try `head --help' for more information.
$ head '-5.' file
head: invalid trailing option -- .
Try `head --help' for more information.
$ head '-5 ' file
head: invalid trailing option --
Try `head --help' for more information.
回答by Mark Setchell
Change this line
改变这一行
LINE=$(echo $SCRIPTNUM | python leetSolver.py)
to
到
LINE=$(echo $SCRIPTNUM | python leetSolver.py | tr -d '\r\n ')
that will remove any trailing line feeds or carriage returns or spaces.
这将删除任何尾随换行符或回车符或空格。
Or, if you prefer sed
或者,如果你喜欢 sed
LINE=$(echo $SCRIPTNUM | python leetSolver.py | sed 's/[^0-9]//g' )
Or, if you like tr
或者,如果你喜欢 tr
LINE=$(echo $SCRIPTNUM | python leetSolver.py | tr -cd '[:digit:]' )
will remove all non-digits.
将删除所有非数字。