最近刚开始学写shell脚本,这里记录一下心得。
我要实现的功能:
->
shell脚本中打开json文件(是一个dict),根据key值匹配value,并对value进行修改。
json文件长这样:
{ “gpu”: “0”, “test_dir”: “test”, … }
我需要提取“test_dir”这个键值,并且将其value改成“train”,需要用到的命令,参考:
sed -i 's/"test_dir":[^,]*/"test_dir":"test"/g' filename.json
->
使用grep的-o和-E选项可以进行正则的精确匹配。
还是上面的例子,想要提取出“test”这个value,可以这么写,参考:
grep -o -E 'test_dir":[^,]*' filename.json |awk -F: '{print $2}'
->
shell脚本的for用法:
for i in train test
do
echo $i #两次循环分别输出 train和test
done
->
shell脚本的if用法:
if 条件; then
echo $a
else
echo $b
fi