使用shell工具提取文件的部分内容

3
我有一个文本文件,想要提取每一行在 !--- comment ---! 上方的内容,并将其存入一个新文件中,不基于行号(但会检查注释)。我该如何做?
test123
bob
ted
mouse
qwerty
!--- comment ---!
123456
098786
4个回答

1

对于文件,如果您的sed程序提前停止,这并不重要;对于管道输入,如果您提前停止,某些程序可能会感到不满。对于这些情况,您应该从注释开始删除:

sed '/^!--- comment ---!$/,$d' somefile.txt

如果你真的必须使用bash而不是像sed这样的shell工具,那么:
x=1
while read line
do
    if [ "$line" = "!--- comment ---!" ]
    then x=0    # Or break
    elif [ $x = 1 ]
    then echo "$line"
    fi
done < somefile.txt

该代码也适用于Bourne和Korn shells,并且我认为它将适用于几乎所有基于Bourne shell(例如任何符合POSIX的shell)的shell。


1

使用sed或while循环

while read line
do
    if [[ $line = '!--- comment ---!' ]];
    then
        break;
    else
        echo $line;
    fi;
done < input.txt > output.txt

1
sed -n '/^!--- comment ---!$/q;p' somefile.txt

0
awk '/!--- comment ---!/ {exit} 1' somefile.txt

如果注释是变量:
awk -v comment="$comment_goes_here" '$0 ~ comment {exit} 1' somefile.txt

尾随的1指示awk对于所有未匹配的行仅使用默认操作(打印)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接