编程题:多条shell脚本中的变量替换

题目:

给定多条shell脚本,求最后一条shell中变量的完整值。其中每条脚本中“=”左侧为变量名,等号右侧中以“${”和“}”包围起来的是需要替换的变量名,例如

tencent=qq${wx}
wx=weixin

tencent=qqweixin
输入示例:

4
x=root/${y}/host
y=net
z=tomcat
last=/home/${x}/local/${z}/com

输出示例:

/home/root/net/host/local/tomcat/com

规定:

①不存在交叉引用,即不会出现类似下列情况:

x=${y}
y=${x}

②可能存在某变量的引用变量在该条脚本后面出现,如:

x=${y}
y=z

③除输入第一行为表示脚本行数的数字外,其余均为字符串。

解题思路

思路:递归。首先读取输入,将除最后一行的脚本之外的脚本以dict形式存储,构建递归函数,处理最后一行脚本。

import sys
in_list = []
for line in sys.stdin:
    sh_cnt = int(line.split()[0])
    if sh_cnt!=0:
        for i in range(sh_cnt):#存储
            sh_item = input()
            sh_item = sh_item.split()[0]
            in_list.append(sh_item)#字符串
        break
    else:
        break

back_str_list = in_list[:-1]#除去最后一个
out_str_org = in_list[-1]#最后一行
back_str_dict = dict()#将所有变量以dict形式存储

#定义字符串转dict函数
def str_2_dict(in_list, in_dict):
    for in_list_i in in_list:
        split_list = in_list_i.split('=')#分拆
        in_dict[split_list[0]] = split_list[1]#存进dict
str_2_dict(back_str_list, back_str_dict)

#定义递归函数
def digui_process(in_str, in_dict):
    out_str = in_str
    if "${" in out_str and "}" in out_str:
        #查找变量位置
        cnt = out_str.count("${")
        for cnt_i in range(cnt):
            front = out_str.find("${")
            tmp_str = out_str#使用tmp_str而不是直接使用out_str确保front索引有效
            out_str = tmp_str[:front]#截取待替换前字符串保存到out_str
            rest_str = tmp_str[front+2:]
            end = rest_str.find("}")
            if end!=-1:#存在配对
                bianliang_str = rest_str[:end]
                bianliang_value = in_dict[bianliang_str]
                out_str += digui_process(bianliang_value, in_dict)
                out_str+=rest_str[end+1:]
            else:
                out_str+=rest_str#不存在配对则直接合并
    #     return out_str
    # else:#如果不存在需要替换的变量
    #     return in_str
    return out_str#以上三行合并成此条return

split_index = out_str_org.find('=')#去掉最后一行脚本的变量名和“=”,按格式输出
print(digui_process(out_str_org, back_str_dict)[split_index+1:])

输入输出:
输入输出

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TracelessLe

❀点个赞加个关注再走吧❀

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值