我正在尝试
1)在文本文件的顶部查找计数器值(3)
2)在THAT行中读德语单词(Kellnerin)
3)在第2行(4)中插入具有递增值的新行
4)删除原始的第1行(3)
5)最后在Firefox上的URI中启动一个网站
German_words.txt:
3
Ufer
Küste
Kellnerin
Bestellung
Gemütlichkeit
bash脚本:
GERMAN_FILE="/home/to/Desktop/German_words.txt"
echo $GERMAN_FILE
getword() {
WORD_NUM=$(awk 'FNR == 1' "$1")
if [[ $WORD_NUM == '' ]] ; then
#Reach end of file
WORD_NUM=1
fi
#Insert the incremented number below Line 1, i.e., Line 2
sed -i '1i((WORD_NUM++))' "$1"
#Delete the previous entry in Line 1
sed -i '1d' "$1"
echo $(awk 'FNR == $WORD_NUM {print; exit}')
}
getword $GERMAN_FILE
/usr/bin/firefox "https://dict.tu-chemnitz.de/dings.cgi?service=deen&opterrors=0&optpro=0&query=${getword}&iservice="
在在线bash编辑器上测试它时,出现以下错误,即https://www.tutorialspoint.com/execute_bash_online.php:
$bash -f main.sh
/home/to/Desktop/German_words.txt
awk: fatal: cannot open file `/home/to/Desktop/German_words.txt' for reading (No such file or directory)
sed: can't read /home/to/Desktop/German_words.txt: No such file or directory
sed: can't read /home/to/Desktop/German_words.txt: No such file or directory
main.sh: line 24: /usr/bin/firefox: No such file or directory
我的问题:
1)有人可以解释为什么我收到“无法打开文件”错误吗?
2)总的来说,我不确定会有更好的解决方案。我无法获得“ sed”替换命令,即sed 's/.../.../' file
工作正常...
答案 0 :(得分:0)
我不确定您为什么会认为在线bash
编辑/执行者会:
除非可以安排其中之一,否则必须在可用文件 的本地测试脚本。
哦,顺便说一句,我看不到它工作得很好:
echo $(awk 'FNR == $WORD_NUM {print; exit}')
由于未指定输入文件,它将永远等待用户输入。
对于更“优雅”的解决方案,看起来您有一个带有当前单词指示符且每行一个单词的文件,例如(抱歉,我的德语非常有限):
1
Ja
Nein
Bitte
Danke
以下功能(以及完整的测试工具)显示了如何执行此操作:
#!/usr/bin/env bash
getword() {
# Get the current word.
awk <gw.in '
FNR == 1 { wordNum = $0 + 1 }
FNR == wordNum { print }'
# Update the current word pointer:
# - get point where it wraps;
# - create new file with new pointer, taking wrap into account;
# - move new file into old.
wrapAt=$(wc -l <gw.in)
awk -vwrapNum=${wrapAt} <gw.in >gw.in.next '
FNR == 1 {
wordNum = $0
nextNum = wordNum + 1
if (nextNum == wrapNum) {
nextNum = 1
}
$0 = nextNum
}
{ print }'
[[ $? -eq 0 ]] && mv gw.in.next gw.in
}
# Test harness.
printf "1\nJa\nNein\nBitte\nDanke\n" >gw.in
echo "=== Before, file is: $(echo $(cat gw.in))"
for ((i = 1; i < 10; ++i)) ; do
word="$(getword)"
echo "=== After word # $i: ${word}, file is: $(echo $(cat gw.in))"
done
运行该测试工具,我们可以看到单词正确输入,并且文件已根据需要进行了更新:
=== Before, file is: 1 Ja Nein Bitte Danke
=== After word # 1: Ja, file is: 2 Ja Nein Bitte Danke
=== After word # 2: Nein, file is: 3 Ja Nein Bitte Danke
=== After word # 3: Bitte, file is: 4 Ja Nein Bitte Danke
=== After word # 4: Danke, file is: 1 Ja Nein Bitte Danke
=== After word # 5: Ja, file is: 2 Ja Nein Bitte Danke
=== After word # 6: Nein, file is: 3 Ja Nein Bitte Danke
=== After word # 7: Bitte, file is: 4 Ja Nein Bitte Danke
=== After word # 8: Danke, file is: 1 Ja Nein Bitte Danke
=== After word # 9: Ja, file is: 2 Ja Nein Bitte Danke