简体   繁体   English

如何使用 bash shell 脚本读取文件中的特定单词并存储在 arrays

[英]how to read after a specific word in a file using bash shell scripting and store in arrays

i am new to linux and bash, here is my question:我是 linux 和 bash 的新手,这是我的问题:

my file (dff.v) has following lines我的文件(dff.v)有以下几行

input a,b;
input [2:0] c;
output [2:0] d;

I have to read the file and store input variables(a,b,[2:0] c) and output variables ([2:0] d) in two different arrays,so that i can use them for further processing.我必须读取文件并将输入变量(a,b,[2:0] c)和 output 变量([2:0] d)存储在两个不同的 arrays 中,以便我可以使用它们进行进一步处理。 I have tried below code to store input variables but i am not getting it as expected.我试过下面的代码来存储输入变量,但我没有按预期得到它。

#!/bin/bash
#assume same directory of file
counta=0;
IFS=','
for i in $(grep -w input dff.v|sed 's/[ ]//1'|sed 's/[;]//g' | sed 's/input//g');
do
 x""$counta"=$i;
 echo $i
 ((counta=counta+1))
done 

i thought the variables will be stored as x0,x1,x2... please help!!我认为变量将存储为 x0,x1,x2 ...请帮助!

You want to dynamically create vars?您想动态创建变量吗? It's imposible this way x"$counta"=$i , but there are some tricks that may help:这种方式是不可能的x"$counta"=$i ,但有一些技巧可能会有所帮助:

read x"$counta" <<< "$i"

Or或者

printf -v x"$counta" "$i"

Or或者

declare x"$counta"="$i"

But i'd suggest use arrays instead:但我建议改用 arrays :

while read name value; do
    value=${value//[\[\];]}
    case $name in
        input ) input+=("$value");;
        output) output+=("$value");;
    esac
done < dff.v

echo "input:  ${input[@]}"
echo "output: ${output[@]}"

$ ./test
input:  a,b 2:0 c
output: 2:0 d

Given the file diff.v and it's content.给定文件 diff.v 及其内容。

baz
input a,b;
blah
input [2:0] c;
foo
output [2:0] d;
more

With a while read loop, and remove the strings that your sed is removing.使用 while 读取循环,并删除sed正在删除的字符串。

#!/usr/bin/env bash

i=0
while read -r input_output lines; do
  [[ $input_output == @(input|output) ]] || continue
  lines=${lines//[][;]}
  printf -v x$i '%s' "$lines"
  ((i++))
done < diff.v

printf '%s\n' "$x0" "$x1" "$x2"

The output output

a,b
2:0 c
2:0 d

Storing the values in an associative array.将值存储在关联数组中。

#!/usr/bin/env bash

i=0
while read -r input_output lines; do
  [[ $input_output == @(input|output) ]] || continue
  lines=${lines//[][;]}
  declare -A array["x$i"]="$lines"
  ((i++))
done < diff.v

printf '%s\n' "${array[x0]}" "${array[x1]}" "${array[x2]}"

Although if you just want to have a quick check what is the value of the array.虽然如果你只是想快速检查一下数组的值是什么。

declare -p array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM