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

phu*_*ehe 35 text-processing

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

我有一个带有很多括号的文本文件,其中一个丢失了!是否有任何程序/脚本/vim 插件/任何可以帮助我识别不匹配括号的东西?

Sha*_*dur 25

在 Vim 中,您可以使用[]快速移动到下一次击键中输入的类型的最近的未匹配括号。

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

  • 我还要补充一点,在 vim 中,您可以使用 %(美国的 Shift 5)立即找到您所在的括号的 _matching_ 括号。 (7认同)
  • 幸运的是,这不适用于括号。`[[` 和 `]]` 实际上分别转到第一列中的下一个打开/关闭的 *brace*。 (3认同)

Pet*_*r.O 8

更新 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  (   )    (         (         (     )   )                    
Run Code Online (Sandbox Code Playgroud)

这是脚本...


#!/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
Run Code Online (Sandbox Code Playgroud)

  • 这很棒,但无论我尝试哪个文件,它似乎总是打印“行,列(8, 10)”。还设置了 `mogXCt=${#mogX}`,但未在任何地方使用。 (2认同)

aso*_*ove 5

最好的选择是由 Shadur 确定的 vim/gvim,但如果你想要一个脚本,你可以在Stack Overflow上查看对类似问题的回答。我在这里重复我的整个答案:

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

首先,您将不得不担心注释和字符串。如果您想在使用正则表达式的编程语言上检查这一点,这将使您的探索再次变得更加困难。

因此,在我进入并就您的问题提供任何建议之前,我需要了解您的问题领域的局限性。如果您可以保证没有字符串,没有注释和正则表达式需要担心 - 或者更一般地说,在代码中没有任何地方可以使用括号,除了用于检查它们是否平衡的用途之外 - 这将让生活简单很多。

了解您要检查的语言会有所帮助。


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

我会简单地寻找并删除所有内括号对:那些里面没有括号的对。这最好通过将所有行折叠成一个长行来完成(并找到一种机制来添加行引用,如果您需要获取该信息)。在这种情况下,搜索和替换非常简单:

它需要一个数组:

B["("]=")"; B["["]="]"; B["{"]="}"
Run Code Online (Sandbox Code Playgroud)

并循环遍历这些元素:

for (b in B) {gsub("[" b "][^][(){}]*[" B[b] "]", "", $0)}
Run Code Online (Sandbox Code Playgroud)

我的测试文件如下:

#!/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)
}
Run Code Online (Sandbox Code Playgroud)

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

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
    }
  '
Run Code Online (Sandbox Code Playgroud)

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

第 3/ 点可能是一个可利用的结果,尽管我不确定您想到的报告机制。

第 2/ 点相对容易实现,但需要花费几分钟以上的时间来制作,所以我将把它留给你来弄清楚。

第 1/ 点是棘手的,因为您进入了一个全新的领域,有时会出现嵌套的开头和结尾,或者特殊字符的特殊引用规则......

  • 谢谢,你救了我。在 30k 行的 json 文件中有一个不匹配的大括号。 (2认同)