我正在循环文件中的行。我只需要跳过以“#”开头的行。我怎么做?
#!/bin/sh
while read line; do
if ["$line doesn't start with #"];then
echo "line";
fi
done < /tmp/myfile
谢谢你的帮助!
while read line; do
case "$line" in \#*) continue ;; esac
...
done < /tmp/my/input
然而,坦率地说,转向grep
:
grep -v '^#' < /tmp/myfile | { while read line; ...; done; }
这是一个老问题,但我最近偶然发现了这个问题,所以我也想分享我的解决方案。
如果你不反对使用一些 python 技巧,这里是:
让它成为我们的名为“my_file.txt”的文件:
this line will print
this will also print # but this will not
# this wont print either
# this may or may not be printed, depending on the script used, see below
让它成为我们的 bash 脚本,名为“my_script.sh”:
#!/bin/sh
line_sanitizer="""import sys
with open(sys.argv[1], 'r') as f:
for l in f.read().splitlines():
line = l.split('#')[0].strip()
if line:
print(line)
"""
echo $(python -c "$line_sanitizer" ./my_file.txt)
调用脚本将产生类似于:
$ ./my_script.sh
this line will print
this will also print
注意:空白行没有打印
如果您想要空行,您可以将脚本更改为:
#!/bin/sh
line_sanitizer="""import sys
with open(sys.argv[1], 'r') as f:
for l in f.read().splitlines():
line = l.split('#')[0]
if line:
print(line)
"""
echo $(python -c "$line_sanitizer" ./my_file.txt)
调用此脚本将产生类似于:
$ ./my_script.sh
this line will print
this will also print