我有一个文本文件,想要提取每一行在 !--- comment ---! 上方的内容,并将其存入一个新文件中,不基于行号(但会检查注释)。我该如何做?
test123
bob
ted
mouse
qwerty
!--- comment ---!
123456
098786
对于文件,如果您的sed程序提前停止,这并不重要;对于管道输入,如果您提前停止,某些程序可能会感到不满。对于这些情况,您应该从注释开始删除:
sed '/^!--- comment ---!$/,$d' somefile.txt
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。
使用sed或while循环:
while read line
do
if [[ $line = '!--- comment ---!' ]];
then
break;
else
echo $line;
fi;
done < input.txt > output.txt
sed -n '/^!--- comment ---!$/q;p' somefile.txt
awk '/!--- comment ---!/ {exit} 1' somefile.txt
awk -v comment="$comment_goes_here" '$0 ~ comment {exit} 1' somefile.txt
1
指示awk对于所有未匹配的行仅使用默认操作(打印)。