[英]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.