我有一行类似于下面的文件finalinput.txt
美国东部时间2021年4月9日下午10:52:35 c1d99c1af08ce4电子邮箱:4277b446:178b8700262:-80000-00000000000 19a8b 1618023155272我在下面写了一个小代码子测试.sh
keyinput="c1d99c1af08ce4ae:-4277b446:178b8700262:-8000-0000000000019a8b"
for line in $(cat finalinput.txt)
do
if $line | grep "$keyinput" > /dev/null; then
echo -e "$date $timen" >> timeoutput.txt
fi
done
output :
line 20: Apr: command not found
./subtest.sh: line 20: 9,: command not found
./subtest.sh: line 20: 2021: command not found
./subtest.sh: line 20: 10:52:35: command not found
./subtest.sh: line 20: PM: command not found
./subtest.sh: line 20: EDT: command not found
./subtest.sh: line 20: c1d99c1af08ce4ae:-4277b446:178b8700262:-8000-0000000000019a8b: command not found
./subtest.sh: line 20: 1618023155272: command not found
./subtest.sh: line 20: ###Update: command not found
./subtest.sh: line 20: Assignment: command not found
./subtest.sh: line 20: Milestone: command not found
./subtest.sh: line 20: Apr: command not found
./subtest.sh: line 20: 9,: command not found
./subtest.sh: line 20: 2021: command not found
./subtest.sh: line 20: 10:52:37: command not found
./subtest.sh: line 20: PM: command not found
./subtest.sh: line 20: EDT: command not found
请帮我找错的地方
您应该首先修复明显的外壳检查错误:
Line 1:
keyinput="c1d99c1af08ce4ae:-4277b446:178b8700262:-8000-0000000000019a8b"
^-- SC2148: Tips depend on target shell and yours is unknown. Add a shebang or a 'shell' directive.
Line 3:
for line in $(cat finalinput.txt)
^-- SC2013: To read lines rather than words, pipe/redirect to a 'while read' loop.
Line 6:
echo -e "$date $timen" >> timeoutput.txt
^-- SC2154: date is referenced but not assigned (for output from commands, use "$(date ...)" ).
^-- SC2154: time is referenced but not assigned (for output from commands, use "$(time ...)" ).
修复SC2013读取时https://mywiki.wooledge.org/BashFAQ/001。阅读关于何时在shell中使用引号何时在shell变量周围使用引号。
哪里我错了
$line
执行一个命令,该命令的名称源自变量line
的扩展。您希望将line
变量的内容作为输入传递给grep
。您想要:
if echo "$line" | grep "$keyinput" > /dev/null; then
但最好是:
if printf "%sn" "$line" | grep -q "$keyinput"; then
总的来说,在bash中你可以:
if grep -q "$keyinput" <<<"$line"; then
实际上,whle脚本只是从文件中读取行。。。grep
就是这么做的。
if grep "$keyinput" finalinput.txt; then
此外,CCD_ 6与CCD_ 7完全相同。