[英]How to read a CSV File and store it in the form of arrays Bash script?
[英]how to read after a specific word in a file using bash shell scripting and store in arrays
我是 linux 和 bash 的新手,这是我的问题:
我的文件(dff.v)有以下几行
input a,b;
input [2:0] c;
output [2:0] d;
我必须读取文件并将输入变量(a,b,[2:0] c)和 output 变量([2:0] d)存储在两个不同的 arrays 中,以便我可以使用它们进行进一步处理。 我试过下面的代码来存储输入变量,但我没有按预期得到它。
#!/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
我认为变量将存储为 x0,x1,x2 ...请帮助!
您想动态创建变量吗? 这种方式是不可能的x"$counta"=$i
,但有一些技巧可能会有所帮助:
read x"$counta" <<< "$i"
或者
printf -v x"$counta" "$i"
或者
declare x"$counta"="$i"
但我建议改用 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
给定文件 diff.v 及其内容。
baz
input a,b;
blah
input [2:0] c;
foo
output [2:0] d;
more
使用 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"
output
a,b
2:0 c
2:0 d
将值存储在关联数组中。
#!/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]}"
虽然如果你只是想快速检查一下数组的值是什么。
declare -p array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.