[英]substring in bash failing: syntax error near unexpected token `done'.
I'm trying to loop through a log file and grab a portion of a string. 我正在尝试遍历日志文件并获取一部分字符串。
The log file contains: 日志文件包含:
Variable_name Value
Slave_running ON
First I need to see if the current row contains the substring Slave_running
(13 characters long starting at position 0). 首先,我需要查看当前行是否包含子串Slave_running
(从位置0开始长13个字符)。 If I get a match, then I need to test what is a character to the right of the same string (14:2). 如果我得到一个匹配,那么我需要测试同一个字符串(14:2)右边的字符是什么。
Here's my feeble attempt to first just print the substring to console: 这是我首先将子串打印到控制台的微弱尝试:
while read p; do
echo ${$p:0:13}
done <slaverunning.log
This returns: 返回:
syntax error near unexpected token `done'.
What am I getting wrong with the bash substring syntax wrong? 我对bash substring语法出错的错误是什么?
Firstly, the issue with your code is just a syntactical one, you don't need the $
before p
, only before {
. 首先,你的代码的问题只是一个语法问题,你不需要在p
之前的$
,只有{
。 The below should work as expected: 以下应该按预期工作:
while read p; do
echo ${p:0:13}
done < slaverunning.log
That said, awk seems to be a better fit for this problem, something like this: 也就是说,awk似乎更适合这个问题,如下所示:
awk '/^Slave_running/ { if ($2 == "ON") { print "running"; } }' slaverunning.log
A great walkthrough of Bash's string manipulation functions: http://www.thegeekstuff.com/2010/07/bash-string-manipulation/ Bash字符串操作函数的一个很棒的演练: http : //www.thegeekstuff.com/2010/07/bash-string-manipulation/
A good place to get familiar with Awk: http://www.grymoire.com/Unix/Awk.html 熟悉Awk的好地方: http : //www.grymoire.com/Unix/Awk.html
There's a syntax error, but it's not about unexpected token... 有一个语法错误,但它不是意外的令牌......
The $p
inside the ${...}
is wrong, this should give a bad substitution
error: ${...}
的$p
是错误的,这应该会导致错误的bad substitution
错误:
echo ${$p:0:13}
With that fixed, your script should work: 修复后,您的脚本应该工作:
while read p; do
echo ${p:0:13}
done <slaverunning.log
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.