0

我有一个在我的 OpenSuSE 机器上运行的 Bash 脚本,但是当复制到我的 Ubuntu 机器时,它不起作用。脚本从文件中读取。该文件具有由空格(制表符和空格)分隔的字段。

#!/bin/bash
function test1()
{
    while read LINE
    do
        if [[ $LINE =~ "^$" || $LINE =~ "^#.*" ]] ; then
            continue;
        fi
        set -- $LINE
        local field1=$1
        local field2=$2
    done < test.file
}

test1

与 test.file 包含:

# Field1Header    Field2Header
abcdef            A-2
ghijkl            B-3

似乎有两个问题:

(1) $field2,带连字符的那个,是空白的

(2) 去除以# 开头的空行和行的正则表达式不起作用

有谁知道怎么了?正如我所说,它在 OpenSuSE 上运行良好。

谢谢,保罗

4

3 回答 3

3
  1. Quoting is wrong, that probably accounts for the regex failing.
  2. No need to use bashisms.
  3. No need to use set

Try

while read field1 field2 dummy
do
    if ! test "${field1%%#*}"
    then
        continue
    fi
    # do stuff here
done

EDIT: The obvious version using set

while read -r line
do
    if ! test "${line%%#*}"
    then
        continue
    fi
    set -- $line
    do_stuff_with "$@"
done
于 2012-07-03T15:10:47.893 回答
3

Apparently, as of bash 3.2 the regular expression should not be quoted. So this should work:

#!/bin/bash
while read LINE
do
    if [[ $LINE =~ ^$ || $LINE =~ ^#.* ]] ; then
        continue;
    fi
    set -- $LINE
    local field1=$1
    local field2=$2
done < test.file

Edit: you should probably use Jo So's answer as it's definitely cleaner. But I was explaining why the regex fails and the reason behind the different behavior between OpenSuse and Ubuntu(different version of bash, very probably)

于 2012-07-03T15:11:22.827 回答
-2

On my ubuntu there is no expresion like "=~" for test command. Just use this one:

if [[ $LINE = "" || ${LINE:0:1} = "#" ]] ; then
    continue;
fi
于 2012-07-03T15:10:32.523 回答