在Shell脚本中使用文件中的键/值数据 [英] Use key/value data from a file in a shell script
问题描述
我有一个名为Year.txt的文件
I have a file called Year.txt
Year2000= 1/2/3/4/
Year2001= 5/6/7/8/
Year2002= 9/10/11/12/
....
....
....
Year2020= 100/101/102/
等等
我需要将此Year.txt作为另一个脚本中的sample.sh的参考
I need to take this Year.txt as reference in my another script some sample.sh
sample.sh
source /home/user/Year.txt
d=cp $filename $1
echo $d
sample.sh Year2000(将Year2000作为第一个参数)
**如果我通过Year2000作为参数,则需要在=之后剪切第二部分,并将此1/2/3/4/粘贴到我的声明中
**I need to cut the second part after = if I pass Year2000 as my argument and paste this 1/2/3/4/ in my statement
**如果我通过Year2001作为参数,我需要在=之后剪切第二部分,并将其5/6/7/8/粘贴到我的复制语句中 等.
**I need to cut the second part after = if I pass Year2001 as my argument and paste this 5/6/7/8/ in my copy statement etc..
我需要这样的输出:
输入1 sample.sh Year2000
输出 :cp somefile.txt 1/2/3/4/
Output: cp somefile.txt 1/2/3/4/
输入2:sample.sh,2001年
输出 :cp somefile.txt 5/6/7/8/
Output: cp somefile.txt 5/6/7/8/
简而言之-我需要从另一个文件中获取引用并生成复制语句
In Short -- I need to take the reference from another file and generate the copy statement
推荐答案
不要source
不是合法bash代码的文件.在这种情况下,关联数组可让您在单个变量中存储所需数量的键/值对.
Don't source
files that aren't legal bash code. In this case, an associative array lets you store as many key/value pairs as you need inside a single variable.
#!/usr/bin/env bash
case $BASH_VERSION in ''|[123].*) echo "ERROR: Needs bash 4.0 or newer" >&2; exit 1;; esac
year_name=$1
file_name=$2
[[ $file_name ]] || { echo "Usage: $0 year-name file-name" >&2; exit 1; }
# Read year.txt, and generate a map
declare -A dirs_by_year=( )
while IFS='= ' read -r k v; do
dirs_by_year[$k]=$v
done <Year.txt
if ! [[ ${dirs_by_year[$year_name]} ]]; then
echo "ERROR: User specified year $1, but input file does not have a directory for it" >&2
echo " ...defined years follow:" >&2
declare -p dirs_by_year >&2 # print array definition to show what we read
exit 1
fi
# generate and write a cp command
printf '%q ' cp "$file_name" "${dirs_by_year[$year_name]}"
这篇关于在Shell脚本中使用文件中的键/值数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!