在bash中读取(循环)时,用空格读取它;不是逐行的

时间:2014-12-18 02:28:38

标签: bash while-loop

我想问一下如何用空格(\ n)迭代文件的内容,而不是逐行读取。

这是一个简单的网络服务代码:

<?php

    $data = json_decode(file_get_contents('php://input'),true);
    print_r($data);

?>

当我尝试运行我的脚本时:

#!/bin/bash  
. /home/sample.txt

while read LINE; do
     curl -H "Content-Type:application/json -XPOST -k "https://sample/posthere.php" -d '{"info":"'"$info"'","grade":"'"$grade"'"}'
done < /home/sample.txt

/home/sample.txt的内容为:


info="student"
grade="Grade 1"

info="teacher"
grade="Grade 3"

不幸的是,结果是:


Array
(
    [info] => teacher
    [grade] => Grade 3
)
Array
(
    [info] => teacher
    [grade] => Grade 3
)
Array
(
    [info] => teacher
    [grade] => Grade 3
)
Array
(
    [info] => teacher
    [grade] => Grade 3
)
Array
(
    [info] => teacher
    [grade] => Grade 3
)

假设,我希望它是这样的:

Array
(
    [info] => student
    [grade] => Grade 1
)
Array
(
    [info] => teacher
    [grade] => Grade 3
)

我认为我在bash中使用读取LINE 代码时出错了。 任何想法都将受到高度赞赏。

2 个答案:

答案 0 :(得分:0)

我个人最喜欢的是:

tr -s ' ' '\n' < input-file | while read ...

也就是说,只需预处理数据并用一个换行符替换所有空格序列。

答案 1 :(得分:0)

当您在脚本顶部找到(或./home/sample.txt时,它会执行以下操作:

  • info设为student
  • grade设为Grade 1
  • info设为teacher
  • grade设为Grade 3

因此,完成后,info设置为teachergrade设置为Grade 3

然后只有对于输入文件中的每一行,您只需使用这两个固定的值,这就是您获得所看到的输出的原因(每行teacher/Grade 3。)

您要做的是按照您的方式处理每一行,并执行相应的操作:

#!/bin/bash

doSomethingWith() {
    echo "Doing something with [$1] [$2]"
}

# Process every line.

while read LINE; do
    if [[ $LINE =~ "info=\"" ]] ; then    # Store info lines.
        info=${LINE:6}                    # Remove [line="] at start.
        info=${info%%\"}                  # Remove ["] at end.
    fi

    if [[ $LINE =~ "grade=\"" ]] ; then   # Act on grade lines.
        grade=${LINE:7}                   # Remove [grade="] at start.
        grade=${grade%%\"}                # Remove ["] at end.
        doSomethingWith "$info" "$grade"  # Process it.
    fi
done < sample.txt