使用Bash读取文件中的行并使用#避免行 [英] Reading lines in a file and avoiding lines with # with Bash
问题描述
我尝试过:
file="myfile"
while read -r line
do
[[ $line = \#* ]] && continue
"address=\$line\127.0.0.1"
done < "$file"
此代码无法避免以注释开头的行.即使我没有任何评论,dnsmasq
也会告诉您有错误.
This code doesn't avoid the lines that begin with comments. Even if I don't have any comments, dnsmasq
tells that there are errors.
它将是一个dnsmasq
conf文件,它将读取并插入域名,如下所示:address=\mydomain.com\127.0.0.1
.
Its going to be a dnsmasq
conf file, and it will read and insert domain names like so: address=\mydomain.com\127.0.0.1
.
输入文件:
domain1.com
domain2.com
domain3.com
#domain4.com
domain5.com
输出应为:
address=/domain1.com/127.0.0.1
address=/domain2.com/127.0.0.1
address=/domain3.com/127.0.0.1
address=/domain5.com/127.0.0.1
I will drop the script in /etc/dnsmasq.d/ directory so that dnsmaq.conf can process it when dnsmasq
is started.
推荐答案
使用[[ "$line" = "\#*" ]]
顺便说一句,address="\\${line}\\127.0.0.1"
UPD :
如果我理解的正确,则需要将每个未注释的域都更改为address=\domain\127.0.0.1
.使用sed
可以轻松快捷地完成此操作,无需使用bash程序.
If I've understand you right you need to change every uncommented domains to address=\domain\127.0.0.1
. It could be done fast and easy with sed
, there is no need in bash-program.
$> cat ./text
domain1.com
domain2.com
domain3.com
#domain4.com
domain5.com
$> sed -r -e 's/(^[^#]*$)/address=\/\1\/127.0.0.1/g' ./text2
address=/domain1.com/127.0.0.1
address=/domain2.com/127.0.0.1
address=/domain3.com/127.0.0.1
#domain4.com
address=/domain5.com/127.0.0.1
如果您需要删除注释行,sed也可以通过/matched_line/d
If you need to remove commented lines, sed can do it too with /matched_line/d
$> sed -r -e 's/(^[^#]*$)/address=\/\1\/127.0.0.1/g; /^#.*$/d' ./text2
address=/domain1.com/127.0.0.1
address=/domain2.com/127.0.0.1
address=/domain3.com/127.0.0.1
address=/domain5.com/127.0.0.1
UPD2 :如果要在bash脚本中执行所有操作,请修改代码:
UPD2: if you want to do all that stuff inside the bash script, here is your code modification:
file="./text2"
while read -r line; do
[[ "$line" =~ ^#.*$ ]] && continue
echo "address=/${line}/127.0.0.1"
done < "$file"
它的输出是:
address=/domain1.com/127.0.0.1
address=/domain2.com/127.0.0.1
address=/domain3.com/127.0.0.1
address=/domain5.com/127.0.0.1
这篇关于使用Bash读取文件中的行并使用#避免行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!