[英]Remove “#” comment lines from the middle of a file
I want remove comment lines, beginning with "#", from the middle of a file, without removing header comment lines at the top of the file. 我想从文件中间删除以“#”开头的注释行,而又不删除文件顶部的标题注释行。 How can I do this using shell scripts and standard Unix tools? 如何使用Shell脚本和标准的Unix工具做到这一点?
#DO NOT MODIFY THIS FILE.
#Mon Jan 14 22:25:16 PST 2013
/test/v1=1.0
#PROPERTIES P1. <------REMOVE THIS
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
#. P2 PROPERTIES <------REMOVE THIS
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
.................
.................
Output 输出量
#DO NOT MODIFY THIS FILE.
#Mon Jan 14 22:25:16 PST 2013
/test/v1=1.0
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
.................
.................
您可以尝试awk :
awk 'NR==1 || NR==2 || !/^#/' file.txt
If you don't want to use awk: 如果您不想使用awk:
head -n 2 file.txt > output.txt
grep -v "^#.*" file.txt >> output.txt
You want to echo the lines beginning with '#', but only at the beginning, using only bash? 您想回显以“#”开头的行,但仅在开始时仅使用bash? Start with a boolean start=true
; 以boolean start=true
; then go line-by-line, set start=false
when the line doesn't start with #
, and echo each line only if you are at the start or the line does not start with #
. 然后逐行进行,当行不是以#
开头时,设置start=false
,并且仅当您在开头或行不是以#
开头时才回显每行。
Here's the file script
: 这是文件script
:
#!/bin/bash
start=true
while read line; do
if $start; then
if [ "${line:0:1}" != "#" ]; then
start=false
fi
fi
if $start || [ "${line:0:1}" != "#" ]; then
echo "${line}"
fi
done
Running it: 运行它:
$ cat input
#DO NOT MODIFY THIS FILE.
#Mon Jan 14 22:25:16 PST 2013
/test/v1=1.0
#PROPERTIES P1.
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
#. P2 PROPERTIES
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
$ ./script < input
#DO NOT MODIFY THIS FILE.
#Mon Jan 14 22:25:16 PST 2013
/test/v1=1.0
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
/test/p1=1.0
/test/p2=1.0
/test/p3=3.0
/test/p41=4.0
/test/v6=1.0
使用GNU sed,您可以
sed '3,${/^#/d}'
这可能对您有用(GNU sed);
sed '/^[^#]/,$!b;/^#/d' file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.