【问题标题】:How can I remove last dot (period) from a string in bash [duplicate]如何从bash中的字符串中删除最后一个点(句点)[重复]
【发布时间】:2020-07-06 13:01:42
【问题描述】:

在 bash 文件中,我得到一个输入参数 $1。它的末尾可能包含一个点,也可能不像(test.test

我希望在这两种情况下都有test 为其添加扩展名并从中创建例如test.py

【问题讨论】:

  • 好的,问题类似,但是当您搜索以 DOT 结尾时,很难找到以斜线结尾的问题。但是为什么要投反对票?!!

标签: string bash


【解决方案1】:

参数扩展有一个运算符% 用于从扩展末尾修剪字符。

$ set test.
$ echo "$1"
test.
$ echo "${1%.}"
test

如果没有尾随点,则扩展保持不变:

$ set test
$ echo "${1%.}"
test

【讨论】:

    【解决方案2】:

    你可以像这样使用parameter expansions

    yourVar=${1/.}
    echo $yourVar
    

    结果:

    $ ./test.sh "test."
    > test
    $ ./test.sh "test" 
    > test
    

    【讨论】:

    • 假设输入可能有多个句点,这似乎只删除了第一个句点,例如:set test.1.2.3.. ; echo ${1/.} => test1.2.3..
    猜你喜欢
    • 2013-02-03
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多