我有一个包含{
and的文件}
,但我发现有错误。我用grep -c { *
andgrep -c } *
来发现and的个数{
不}
相等。我想找到那些可能有错误的行,所以我可以手动检查它们。
- 右大括号应始终出现在同一行,因此我需要找到
{
没有右大括号的}
行或}
没有左大括号的行。 - 有些行有很多大括号,例如
{ } { } { }
. - 永远不应该有嵌套的大括号,例如`{ { { } } }'。
如何搜索没有正确数量的大括号的行?
我有一个包含{
and的文件}
,但我发现有错误。我用grep -c { *
andgrep -c } *
来发现and的个数{
不}
相等。我想找到那些可能有错误的行,所以我可以手动检查它们。
{
没有右大括号的}
行或}
没有左大括号的行。{ } { } { }
.如何搜索没有正确数量的大括号的行?
你可以做这样的事情(这将打印行和行号) -
gawk -v FS="" '
{cnt=0;for(i=1;i<=NF;i++) if ($i=="{") ++cnt ;
else if ($i=="}") --cnt; if (cnt!=0) print NR":"$0}' file
[jaypal:~/Temp] cat file
this is {random text} some with { some without
purpose is{ to identify such lines} where { dont have a matching }
and print those lines with just one {
[jaypal:~/Temp] gawk -v FS="" '
> {cnt=0;for(i=1;i<=NF;i++) if ($i=="{") ++cnt ;
> else if ($i=="}") --cnt; if (cnt!=0) print NR":"$0}' file
1:this is {random text} some with { some without
3:and print those lines with just one {
这可能对您有用:
sed 'h;y/}/{/;s/[^{]*{[^{]*{[^{]*//g;/./!d;g file
我不在我的电脑前尝试,但我认为这可能有效
grep -v '^\([^{}]*{[^{}]*}[^{}]*\)*$'
如果我写得正确,这应该匹配(所以不打印,因为-v
)只有整行由对组成的行,使得
重复零次或多次。
试试这个代码。它将打印大括号计数不匹配的那些行
#!/bin/bash
LINE_COUNT=1
cat decrypt.txt | while read line
do
i=0
O_B=0
C_B=0
while (( i++ < ${#line} ))
do
char=$(expr substr "$line" $i 1)
#echo $char
if [ "$char" = "{" ]
then
O_B=`expr $O_B + 1`
elif [ "$char" = "}" ]
then
C_B=`expr $C_B + 1`
fi
done
#echo "$line|$O_B|$C_B"
if [ $O_B -ne $C_B ]
then
echo "$LINE_COUNT|$line|$O_B|$C_B"
fi
LINE_COUNT=`expr $LINE_COUNT + 1`
done