回答:
Vimでは[、と]を使用して、次のキーストロークで入力されたタイプの最も近い一致しないブラケットにすばやく移動できます。
その[{ため、最も近い不一致の「{」に戻ります。])一番近い一致しない ")"に進みます。
更新2:
次のスクリプトは、誤ったブラケットの行番号と列を出力するようになりました。これは、スキャンごとに1つのブラケットタイプ処理(すなわち「[]」「<>」「{}」「()」...)
スクリプトを識別最初、不一致右ブラケット、または任意の最初の未対左ブラケット ...エラーを検出すると、行番号と列番号で終了します
以下に出力例を示します...
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
Line, Column (8, 10)どのファイルを試しても、常に印刷されるようです。またmogXCt=${#mogX}、設定されていますが、どこでも使用されていません。
最良のオプションはShadurによって識別されるvim / gvimですが、スクリプトが必要な場合は、Stack Overflowで同様の質問に対する私の答えを確認できます。ここですべての答えを繰り返します。
あなたがしようとしていることが汎用言語に当てはまる場合、これは重要な問題です。
まず、コメントと文字列について心配する必要があります。正規表現を使用するプログラミング言語でこれを確認したい場合、これはあなたの探求を再び難しくします。
それで、私が入ってあなたの質問についてアドバイスをする前に、私はあなたの問題領域の限界を知る必要があります。文字列、コメント、および心配する正規表現がないことを保証できる場合、またはより一般的には、バランスが取れていることを確認している用途以外にブラケットが使用される可能性のあるコードのどこにもありません-これは人生をずっとシンプルにします。
確認したい言語を知っていると役立ちます。
ノイズがない、つまりすべてのブラケットが有用なブラケットであるという仮説を立てると、私の戦略は反復的です。
私は単純にすべての内部ブラケットペアを探して削除します:内部にブラケットを含まないペア。これは、すべての行を1本の長い行に折りたたむ(および、その情報を取得する必要がある場合に行参照を追加するメカニズムを見つける)ことで最適に行われます。この場合、検索と置換は非常に簡単です。
配列が必要です:
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 /はおそらく悪用可能な結果ですが、あなたが念頭に置いていた報告メカニズムについてはわかりません。
ポイント2 /は比較的簡単に実装できますが、作成するのに数分以上かかるので、理解するまでお任せします。
ポイント1 /は、時にはネストされた開始と終了、または特殊文字の特別な引用ルールの競合するまったく新しい領域を入力するため、難しいものです...