如何从 bash shell 中的输入中 trim 最后四个字符?
How to trim last four character from the input in bash shell?
我打算在 C++ 中自动编译和 运行 过程,我将以下代码编写为 compile-run.sh
#! /bin/bash
clang++ .cpp -o .out && ./.out
我把这个 compile-run.sh 放在 /usr/local/bin 中供全局使用,
当我键入命令 compile-run.sh XXX.cpp
时,它打算编译并 运行 指定的 cpp 文件。但现在的问题是我必须手动删除命令中的“.cpp
”。
有什么方法可以trim字符的最后X个数字并一般分配给一个变量吗?
有什么方法可以 trim .cpp
并在代码中应用 trimmed $1 吗?
有没有更好的方法来自动化编译和 运行 过程?
好吧,一个丑陋的方法可能是使用类似的东西:
#! /bin/bash
filename=
temp="${filename%%.cpp}"
clang++ $temp.cpp -o $temp.out && ./$temp.out
另一种方式,如果您想 trim 最后 4 个字符,无论最后一部分是什么:
#! /bin/bash
filename=
temp="${filename::-4}"
clang++ $temp.cpp -o $temp.out && ./$temp.out
但对于子字符串,您也可以使用 cut: 即。 https://stackabuse.com/substrings-in-bash/
我打算在 C++ 中自动编译和 运行 过程,我将以下代码编写为 compile-run.sh
#! /bin/bash
clang++ .cpp -o .out && ./.out
我把这个 compile-run.sh 放在 /usr/local/bin 中供全局使用,
当我键入命令 compile-run.sh XXX.cpp
时,它打算编译并 运行 指定的 cpp 文件。但现在的问题是我必须手动删除命令中的“.cpp
”。
有什么方法可以trim字符的最后X个数字并一般分配给一个变量吗?
有什么方法可以 trim .cpp
并在代码中应用 trimmed $1 吗?
有没有更好的方法来自动化编译和 运行 过程?
好吧,一个丑陋的方法可能是使用类似的东西:
#! /bin/bash
filename=
temp="${filename%%.cpp}"
clang++ $temp.cpp -o $temp.out && ./$temp.out
另一种方式,如果您想 trim 最后 4 个字符,无论最后一部分是什么:
#! /bin/bash
filename=
temp="${filename::-4}"
clang++ $temp.cpp -o $temp.out && ./$temp.out
但对于子字符串,您也可以使用 cut: 即。 https://stackabuse.com/substrings-in-bash/