我刚刚开始学习bash并且我正在尝试编写一个接受两个单词作为参数的脚本,并在找到第一个单词的行和找到第二个单词的行之间打印出给定文件的部分,例如我的test.txt
文件如下:
This is a line of text
This is another line of text
this is the third one
Another one right here
我用./prog.bash test.txt This one
运行程序它应该返回第1,2和3行,因为我们在第一行找到单词This,在第3行找到第一行。我当前的脚本看起来像:
#!/bin/bash
filename=$1
a=$(grep -n -m1 "$2" "$filename" | cut -f 1 -d':') #find first occurence of word1 and use that to cut the line number of word
b=$(grep -n -m1 "$3" "$filename" | cut -f 1 -d':') #find first occurence of word2 and use that to cut the line number of word
lines=$(($b-$a)+1)
thing= $(head -n"${b}" "$filename" | tail -n"${lines}") #Print out b lines from beginning and then print $(lines) lines from bottom of that
echo $a
echo $b
echo $lines
echo $thing
exit
现在我收到错误说
./ prog.bash:第6行:这:找不到命令
由于该行上的唯一命令是head
和tail
,我查看了路径的位置以及它们的位置,我想出了:
$PATH =
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
head = /usr/bin/head
tail = /usr/bin/tail
答案 0 :(得分:0)
第6行应
thing=$(head -n"${b}" "$filename" | tail -n"${lines}") #Print out b lines from beginning and then print $(lines) lines from bottom of that
=