【问题标题】:shell process and compare array elementshell 处理和比较数组元素
【发布时间】:2021-01-24 07:39:16
【问题描述】:

有一个名为 test.txt 的文件包含:

ljlkfjdslkfldjfdsajflkjf  word:test1
dflkdjflkdfdjls word:test2
dlkdj word:test3
word:test4
word:NewYork
dljfldflkdflkdjf word:test7
djfkd word:young
dkjflke word:lisa
amazonwle word:NewYork
dlksldjf word:test10

现在我们只需要获取冒号后的字符串,如果结果相同,则打印输出,在本例中为“NewYork”

这是列出元素的脚本,但是当尝试推入数组并比较它时失败了,请告诉我我的错误。

#!/usr/bin/sh
input="test.txt"
cat $input | while read line; do output= $(echo $line | cut -d":" -f2);  done
for (( i = 0 ; i < "${#output[@]}" ; i++ ))
{
      echo ${output[i]}
}

得到的错误:

./compare.sh
./compare.sh: line 11: test1: command not found
./compare.sh: line 11: test2: command not found
./compare.sh: line 11: test3: command not found
./compare.sh: line 11: test4: command not found
./compare.sh: line 11: NewYork: command not found
./compare.sh: line 11: raghav: command not found
./compare.sh: line 11: young: command not found
./compare.sh: line 11: lisa: command not found
./compare.sh: line 11: NewYork: command not found
./compare.sh: line 11: test10: command not found

【问题讨论】:

  • 输入文件如下所示:
  • cat test.txt ljlkfjdslkfldjfdsajflkjf word:test1 dflkdjflkdfdjls word:test2 dlkdj word:test3 word:test4 word:NewYork dljfldflkdflkdjf word:kathy djfkd word:young dkjflke word:lisa amazonwle word:NewYork d:
  • 我无法将字符串放入数组然后比较数组元素并打印,请帮助

标签: shell scripting


【解决方案1】:

请让我知道我的错误。

output= $(..) 首先在内部执行命令$(..) 并获取它的输出。然后它将变量output 设置为一个空字符串,就好像与output="" 一样,并导出变量output 并作为命令执行$(..) 的输出。去掉=后面的空格。

您将output 设置在子shell 内管道的右侧。更改将在外部不可见 - 一旦管道终止,output 将被取消设置。使用重定向while .... done &lt; file

output 不是数组,而是普通变量。没有${output[i]}(好吧,除了${output[0]}),因为它不是一个数组(并且output 未设置,如上所述)。将元素附加到数组output+=("$(...)")

#!/usr/bin/sh - 无效,sh 可能不是 bash 并且支持 bash 数组。要使用bash 扩展,请特别使用bash 并使用带有bash - #!/bin/bash 的shebang,

现在的风格:

bash 一直支持for .... { ... } 格式,但它是一种相当未记录的语法,不推荐使用C 编程的人阅读。首选标准do ... done

扩展 $input${output[i]} 未加引号。

read 将忽略前导和尾随空格,并解释/忽略 \ 反斜杠序列(即,参见 read-r 选项)。

echo $line 将使$line 进行分词 - 多个空格将被一个空格替换。

read 之后使用cut 可以更简单地编写为readIFS=: 并在read 上拆分。另外,如果您使用cut,您可以只对整个文件使用cut -d: -f2 file,而不是一次剪切一行。

重新阅读基本的 bash 介绍 - 请注意 bash 是空间感知的,= 周围的空间计数。阅读bashfaq how to read a file field by field,阅读有关子shell 和环境的信息,阅读bashfaq I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read? 和对bash 数组的介绍。

【讨论】:

    猜你喜欢
    • 2018-06-14
    • 2012-06-09
    • 2016-03-25
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多