【问题标题】:Issues with c shell escape character for ** 的 c shell 转义字符问题
【发布时间】:2016-02-18 06:24:11
【问题描述】:

首先,这是家庭作业。只是在努力解决一些我无法通过谷歌找到太多信息的事情。

问题是打印从 1 到输入的数字的整数的乘积。

所以如果我们输入 4,我们给出 24 (1*2*3*4) 作为输出。

我的问题是,我不知道如何转义 * 字符以将其连接到我的字符串。我在 bourne shell 上有这个工作,但在 c shell 中一直遇到这个问题。

@ temp = 1
@ ans = 1
while ( $temp <= $number )
    @ ans = ( $ans * $temp )
    @ temp = ( $temp + 1 )
end
set ans = "$ans ("
@ count = 1
while ( $count <= $number )
    set ans = "$ans$count"
    @ count = ( $count + 1 )
    if ( $count <= $number ) then
        set ans = "$ans*"
    endif
end
set ans = "$ans)"
echo $ans   

任何帮助或指针将不胜感激。 谢谢!

【问题讨论】:

    标签: shell csh


    【解决方案1】:

    罢工>

    set star = "*"
    set ans = "$ans$star"
    

    编辑 How do I escape the wildcard/asterisk character in bash?您的回声需要引用:

    echo "$ans"
    

    【讨论】:

    • 想想这个。实际上在发布之前已经尝试过。我仍然得到一个回声:没有匹配。当试图回应 ans 时。
    • 您正在链接到一个 bash 问题。这是关于 csh 的。
    【解决方案2】:

    在回显变量时,在变量周围使用双引号 (echo "$ans") 以避免 shell 扩展变量值中的元字符:

    (脚本文件:prod.csh):

    #!/bin/tcsh
    
    @ number = 6
    @ temp = 1
    @ ans = 1
    while ( $temp <= $number )
        @ ans = ( $ans * $temp )
        @ temp = ( $temp + 1 )
    end
    set ans = "$ans ("
    @ count = 1
    while ( $count <= $number )
        set ans = "$ans$count"
        @ count = ( $count + 1 )
        if ( $count <= $number ) then
            set ans = "$ans*"
        endif
    end
    set ans = "$ans)"
    echo "$ans"
    

    示例运行:

    $ tcsh prod.csh
    720 (1*2*3*4*5*6)
    $
    

    【讨论】:

    • 顺便说一句,您也可以使用set noglob,这有时很有用,因为在某些情况下添加引号可能会很棘手。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多