如何在文本文件中找到不匹配的括号?


32

今天,我了解到可以用来perl -c filename在任意文件(不一定是Perl脚本)中找到不匹配的大括号{}。问题是,它不能与其他类型的方括号()[]以及<>一起使用。我还对几个Vim插件进行了实验,这些插件声称可以帮助您找到无与伦比的括号,但到目前为止还不是很好。

我有一个带有很多括号的文本文件,其中一个缺少!是否有任何程序/脚本/ vim插件/可以帮助我识别出无与伦比的括号?

Answers:


22

在Vim中,您可以使用[]快速移至下一个击键中输入的最接近的,不匹配的括号。

因此,[{将带您回到最接近的不匹配“ {”;])会带您到最接近的,不匹配的“)”,依此类推。


太好了,这对我来说很完美。我将接受这个答案,但是只是在等待看看是否存在可以对此进行分析的文本处理工具。
phunehehe

6
我还要补充一点,在vim中,您可以使用%(在美国,按Shift 5键)立即找到您所在的括号的匹配括号。
2011年

@atroon Ooo,很好。我自己还不知道那个人。有时我喜欢stackexchange。:)
Shadur

是<kbd> [</ kbd>和<kbd>] </ kbd>真正跳到
wirrbel,2013年

我花了整整一天的时间浏览4000行,以查找R中缺少的},这就是答案。再次感谢VIM!但是我认为这是将源代码文件分成较小块的一个很好的论据。
托马斯·布朗

7

更新2:
现在,以下脚本将打印出格式错误的括号中的行号和列。每次扫描处理一个括号类型(即'[]''<>''{}''()'...)
该脚本标识第一个不匹配的右括号,或任何未配对的左括号中的第一个 ...在检测到错误时,它会以行号和列号退出

这是一些示例输出...


File = /tmp/fred/test/test.in
Pair = ()

*INFO:  Group 1 contains 1 matching pairs

ERROR: *END-OF-FILE* encountered after Bracket 7.
        A Left "(" is un-paired in Group 2.
        Group 2 has 1 un-paired Left "(".
        Group 2 begins at Bracket 3.
  see:  Line, Column (8, 10)
        ----+----1----+----2----+----3----+----4----+----5----+----6----+----7
000008  (   )    (         (         (     )   )                    

这是脚本...


#!/bin/bash

# Itentify the script
bname="$(basename "$0")"
# Make a work dir
wdir="/tmp/$USER/$bname"
[[ ! -d "$wdir" ]] && mkdir -p "$wdir"

# Arg1: The bracket pair 'string'
pair="$1"
# pair='[]' # test
# pair='<>' # test
# pair='{}' # test
# pair='()' # test

# Arg2: The input file to test
ifile="$2"
  # Build a test source file
  ifile="$wdir/$bname.in"
  cp /dev/null "$ifile"
  while IFS= read -r line ;do
    echo "$line" >> "$ifile"
  done <<EOF
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
[   ]    [         [         [
<   >    <         
                   <         >         
                             <    >    >         >
----+----1----+----2----+----3----+----4----+----5----+----6
{   }    {         }         }         }         } 
(   )    (         (         (     )   )                    
ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ
EOF

echo "File = $ifile"
# Count how many: Left, Right, and Both
left=${pair:0:1}
rght=${pair:1:1}
echo "Pair = $left$rght"
# Make a stripped-down 'skeleton' of the source file - brackets only
skel="/tmp/$USER/$bname.skel" 
cp /dev/null "$skel"
# Make a String Of Brackets file ... (It is tricky manipulating bash strings with []..
sed 's/[^'${rght}${left}']//g' "$ifile" > "$skel"
< "$skel" tr  -d '\n'  > "$skel.str"
Left=($(<"$skel.str" tr -d "$left" |wc -m -l)); LeftCt=$((${Left[1]}-${Left[0]}))
Rght=($(<"$skel.str" tr -d "$rght" |wc -m -l)); RghtCt=$((${Rght[1]}-${Rght[0]}))
yBkts=($(sed -e "s/\(.\)/ \1 /g" "$skel.str"))
BothCt=$((LeftCt+RghtCt))
eleCtB=${#yBkts[@]}
echo

if (( eleCtB != BothCt )) ; then
  echo "ERROR:  array Item Count ($eleCtB)"
  echo "     should equal BothCt ($BothCt)"
  exit 1
else
  grpIx=0            # Keep track of Groups of nested pairs
  eleIxFir[$grpIx]=0 # Ix of First Bracket in a specific Group
  eleCtL=0           # Count of Left brackets in current Group 
  eleCtR=0           # Count of Right brackets in current Group
  errIx=-1           # Ix of an element in error.
  for (( eleIx=0; eleIx < eleCtB; eleIx++ )) ; do
    if [[ "${yBkts[eleIx]}" == "$left" ]] ; then
      # Left brackets are 'okay' until proven otherwise
      ((eleCtL++)) # increment Left bracket count
    else
      ((eleCtR++)) # increment Right bracket count
      # Right brackets are 'okay' until their count exceeds that of Left brackets
      if (( eleCtR > eleCtL )) ; then
        echo
        echo "ERROR:  MIS-matching Right \"$rght\" in Group $((grpIx+1)) (at Bracket $((eleIx+1)) overall)"
        errType=$rght    
        errIx=$eleIx    
        break
      elif (( eleCtL == eleCtR )) ; then
        echo "*INFO:  Group $((grpIx+1)) contains $eleCtL matching pairs"
        # Reset the element counts, and note the first element Ix for the next group
        eleCtL=0
        eleCtR=0
        ((grpIx++))
        eleIxFir[$grpIx]=$((eleIx+1))
      fi
    fi
  done
  #
  if (( eleCtL > eleCtR )) ; then
    # Left brackets are always potentially valid (until EOF)...
    # so, this 'error' is the last element in array
    echo
    echo "ERROR: *END-OF-FILE* encountered after Bracket $eleCtB."
    echo "        A Left \"$left\" is un-paired in Group $((grpIx+1))."
    errType=$left
    unpairedCt=$((eleCtL-eleCtR))
    errIx=$((${eleIxFir[grpIx]}+unpairedCt-1))
    echo "        Group $((grpIx+1)) has $unpairedCt un-paired Left \"$left\"."
    echo "        Group $((grpIx+1)) begins at Bracket $((eleIxFir[grpIx]+1))."
  fi

  # On error, get Line and Column numbers
  if (( errIx >= 0 )) ; then
    errLNum=0    # Source Line number (current).
    eleCtSoFar=0 # Count of bracket-elements in lines processed so far.
    errItemNum=$((errIx+1)) # error Ix + 1 (ie. "1 based")
    # Read the skeketon file to find the error line-number
    while IFS= read -r skline ; do
      ((errLNum++))
      brackets="${skline//[^"${rght}${left}"]/}" # remove whitespace
      ((eleCtSoFar+=${#brackets}))
      if (( eleCtSoFar >= errItemNum )) ; then
        # We now have the error line-number
        # ..now get the relevant Source Line 
        excerpt=$(< "$ifile" tail -n +$errLNum |head -n 1)
        # Homogenize the brackets (to be all "Left"), for easy counting
        mogX="${excerpt//$rght/$left}"; mogXCt=${#mogX} # How many 'Both' brackets on the error line? 
        if [[ "$errType" == "$left" ]] ; then
          # R-Trunc from the error element [inclusive]
          ((eleTruncCt=eleCtSoFar-errItemNum+1))
          for (( ele=0; ele<eleTruncCt; ele++ )) ; do
            mogX="${mogX%"$left"*}"   # R-Trunc (Lazy)
          done
          errCNum=$((${#mogX}+1))
        else
          # errType=$rght
          mogX="${mogX%"$left"*}"   # R-Trunc (Lazy)
          errCNum=$((${#mogX}+1))
        fi
        echo "  see:  Line, Column ($errLNum, $errCNum)"
        echo "        ----+----1----+----2----+----3----+----4----+----5----+----6----+----7"  
        printf "%06d  $excerpt\n\n" $errLNum
        break
      fi
    done < "$skel"
  else
    echo "*INFO:  OK. All brackets are paired."
  fi
fi
exit

这个脚本很棒!
乔纳森·杜马因

1
这很棒,但是Line, Column (8, 10)无论我尝试使用哪个文件,它似乎总是可以打印。也mogXCt=${#mogX}已设置,但未在任何地方使用。
克莱顿公爵

5

最好的选择是Shadur标识的vim / gvim,但是如果需要脚本,可以检查Stack Overflow上类似问题的回答。我在这里重复我的全部答案:

如果您尝试做的事情适用于通用语言,那么这是一个不小的问题。

首先,您将不得不担心注释和字符串。如果要在使用正则表达式的编程语言上进行检查,这将使您的搜索再次困难。

因此,在我介入您的问题之前,我需要知道您所遇到问题的范围。如果您可以保证没有字符串,没有注释和正则表达式,则不必担心-或更一般地说,在代码中除了可以检查括号是否平衡的用法之外,括号中也可以不使用括号-这将使生活简单得多。

知道您要检查的语言会有所帮助。


如果我假设没有噪音,即所有方括号都是有用的方括号,那么我的策略将是迭代的:

我只是寻找并删除所有内部括号对:那些里面不包含括号的对。最好通过将所有行折叠成一条长行来完成(并找到一种添加行引用的机制,以备不时之需)。在这种情况下,搜索和替换非常简单:

它需要一个数组:

B["("]=")"; B["["]="]"; B["{"]="}"

循环遍历这些元素:

for (b in B) {gsub("[" b "][^][(){}]*[" B[b] "]", "", $0)}

我的测试文件如下:

#!/bin/awk

($1 == "PID") {
  fo (i=1; i<NF; i++)
  {
    F[$i] = i
  }
}

($1 + 0) > 0 {
  count("VIRT")
  count("RES")
  count("SHR")
  count("%MEM")
}

END {
  pintf "VIRT=\t%12d\nRES=\t%12d\nSHR=\t%12d\n%%MEM=\t%5.1f%%\n", C["VIRT"], C["RES"], C["SHR"], C["%MEM"]
}

function count(c[)
{
  f=F[c];

  if ($f ~ /m$/)
  {
    $f = ($f+0) * 1024
  }

  C[c]+=($f+0)
}

我的完整脚本(无行引用)如下:

cat test-file-for-brackets.txt | \
  tr -d '\r\n' | \
  awk \
  '
    BEGIN {
      B["("]=")";
      B["["]="]";
      B["{"]="}"
    }
    {
      m=1;
      while(m>0)
      {
        m=0;
        for (b in B)
        {
          m+=gsub("[" b "][^][(){}]*[" B[b] "]", "", $0)
        }
      };
      print
    }
  '

该脚本的输出在括号的最内部非法使用处停止。但要注意:1 /此脚本不适用于注释,正则表达式或字符串中的括号; 2 //它不会报告问题在原始文件中的位置; 3 /尽管它将删除所有平衡对,但它会停止在最里面错误条件,并保留所有包围式括号。

尽管我不确定您所考虑的报告机制,但第3点可能是可以利用的结果。

Point 2 /相对易于实现,但是要花几分钟的时间才能完成,因此我将由您自己决定。

点1 /是一个棘手的问题,因为您进入了一个全新的领域,竞争有时是嵌套的开始和结尾,或者是特殊字符的特殊引用规则...


1
谢谢,你救了我。在30k行json文件中有一个不匹配的括号。
I822012年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.