这是我的配置文件(dansguardian- config ):
banned-phrase duck
banned-site allaboutbirds.org我想写一个bash脚本,它将读取此配置文件并为我创建一些其他文件。这是我到目前为止所知道的,大部分都是伪代码:
while read line
do
# if line starts with "banned-phrase"
# add rest of line to file bannedphraselist
# fi
# if line starts with "banned-site"
# add rest of line to file bannedsitelist
# fi
done < dansguardian-config我不确定是否需要使用grep、sed、awk等。
希望这是有意义的。我真的很讨厌DansGuardian列表。
发布于 2013-05-23 05:57:15
你可以这样做
sed -n 's/^banned-phrase *//p' dansguardian-config > bannedphraselist
sed -n 's/^banned-site *//p' dansguardian-config > bannedsitelist尽管这意味着要读取该文件两次。不过,我怀疑可能的性能损失是否重要。
发布于 2013-05-23 05:57:20
您可以一次读取多个变量;默认情况下,它们以空格分隔。
while read command target; do
case "$command" in
banned-phrase) echo "$target" >>bannedphraselist;;
banned-site) echo "$target" >>bannedsitelist;;
"") ;; # blank line
*) echo >&2 "$0: unrecognized config directive '$command'";;
esac
done < dansguardian-config只是作为一个例子。更聪明的实现应该是先读取列表文件,确保没有被禁止,等等。
发布于 2013-05-23 07:21:48
使用echo text >> file的所有解决方案有什么问题?可以用strace检查,在每个这样的步骤中,打开file,然后定位到最后,然后写入text并关闭文件。所以如果有1000次echo text >> file,那么就会有1000次open,lseek,write,close。可以通过以下方式大幅减少open、lseek和close的数量:
while read key val; do
case $key in
banned-phrase) echo $val>&2;;
banned-site) echo $val;;
esac
done >bannedsitelist 2>bannedphraselist <dansguardian-configstdout和stderr被重定向到文件,并在循环活动时保持打开状态。因此,文件只打开一次,然后关闭一次。不需要我的帮助。此外,这种方式更多地使用了文件缓存,因为对close的不必要调用不会每次都刷新缓冲区。
https://stackoverflow.com/questions/16702190
复制相似问题