我的新手 Linux 脚本遇到问题,它需要计算括号数量并判断它们是否匹配。
#!/bin/bash
file="$1"
x="()(((a)(()))"
left=$(grep -o "(" <<<"$x" | wc -l)
rght=$(grep -o ")" <<<"$x" | wc -l)
echo "left = $left right = $rght"
if [ $left -gt $rght ]
then echo "not enough brackets"
elif [ $left -eq $rght ]
then echo "all brackets are fine"
else echo "too many"
fi
这里的问题是我无法通过命令行传递参数,以便 grep 工作并计算文件中的括号。在 $x 的地方我试着写 $file 但它不起作用
我正在通过编写执行脚本:./script.h test1.txt 文件 test1.txt 与 script.h 位于同一文件夹中
如果能帮助解释参数传递的工作原理,那就太好了。或者用其他方式来执行此脚本?
最佳答案
构造 <<<
用于传输“变量的内容”,不适用于“文件的内容”。如果执行此代码段,您就会明白我的意思:
#!/bin/bash
file="()(((a)((a simple test)))"
echo "$( cat <<<"$file" )"
这也相当于 echo "$file"
.也就是说,发送到控制台的是变量"file"的内容。
要获取名为“file”的 var 中的“文件内容”,请执行以下操作:
#!/bin/bash
file="test1.txt"
echo "$( cat <"$file" )"
完全等同于echo "$( <"$file" )"
, cat <"$file"
甚至 <"$file" cat
您可以使用:grep -o "(" <"$file"
或 <"$file" grep -o "("
但是 grep 可以接受一个文件作为参数,所以这个:grep -o "(" "$file"
也有效。
不过,我相信tr
将是一个更好的命令,如下所示:<"$file" tr -cd "("
.
它将整个文件转换为仅“(”的序列,传输(传递)到 wc
命令所需的时间要少得多。您的脚本将变为:
#!/bin/bash -
file="$1"
[[ $file ]] || exit 1 # make sure the var "file" is not empty.
[[ -r $file ]] || exit 2 # test if the file "file" exists.
left=$(<"$file" tr -cd "("| wc -c)
rght=$(<"$file" tr -cd ")"| wc -c)
echo "left = $left right = $rght"
# as $left and $rght are strictly numeric values, this integer tests work:
(( $left > $rght )) && echo "not enough right brackets"
(( $left == $rght )) && echo "all brackets are fine"
(( $left < $rght )) && echo "too many right brackets"
# added as per an additional request of the OP.
if [[ $(<"$file" tr -cd "()"|head -c1) = ")" ]]; then
echo "the first character is (incorrectly) a right bracket"
fi
关于linux - greping 文件 UNIX.linux bash 中的一个字符。无法通过命令行传递参数(文件名),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26219075/