Bash shell 中的错误分隔符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25319492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:08:34  来源:igfitidea点击:

Bad delimiter in Bash shell

bash

提问by Naftaly

I'm trying to iterate over few lines of bash script and echo all the non comment lines.

我正在尝试迭代几行 bash 脚本并回显所有非注释行。

Within my loop I have the following command:

在我的循环中,我有以下命令:

echo $line | cut -d" #" -f1

However the interpreter throws at me the following error:

但是,解释器向我抛出以下错误:

cut: bad delimiter

What I did wrong?

我做错了什么?

采纳答案by Warwick

As mentioned in the comments, the -dparameter to cutexpects only one character. try using nawkinstead for your example:

正如评论中提到的,-d参数 tocut只需要一个字符。尝试使用nawk代替您的示例:

echo $line | nawk 'BEGIN {FS=" #" } ; { print  }'

Or to just print lines that don't begin with a " #", use grep:

或者只打印不以“#”开头的行,请使用grep

grep -v " #" <file>

Or to print only lines that begin with a hash, or just white space and a hash, I'd use Perl:

或者只打印以散列开头的行,或者只打印空格和散列,我会使用 Perl:

perl -n -e 'unless (/(\S+)*#/) {print}' <file>

回答by John B

You could use awk:

你可以使用awk

awk ' !~ /^#/' file

Only prints lines that do not start with a #in the first field.

只打印#第一个字段中不以 a 开头的行。

If you want to test if a string is a comment:

如果要测试字符串是否为注释:

if [[ ! $(awk ' !~ /^#/' <<<"$string") ]]; then
    echo "'$string' is a comment"
else
    echo "'$string' is not a comment"
fi

Or another way using bashonly:

bash仅使用另一种方式:

if [[ ! ${string%\#*} || ${string%\#*} == +([[:space:]]) ]]; then
    echo "'$string' is a comment"
else
    echo "'$string' is not a comment"
fi

回答by zerodiff

Just for completeness, using sed:

只是为了完整性,使用sed

sed '/^\S*#/d' file

This essentially says output all lines that do not start with any whitespace followed by a #. This is a modern version of sed, so older ones you might have to use something else for the whitespace match.

这实质上是说输出所有不以任何空格开头的行,后跟 a #。这是 的现代版本sed,因此较旧的版本您可能必须使用其他东西来进行空白匹配。