日志文件名:"/home/msubra/WORK/tmo/LOG/BCH1043.9987.log"
我需要从上面的字符串中提取内容BCH1043
。
目录结构可能不同,因此解决方案应使用 BCH 检查字符串直到点
最佳答案
无需调用 basename,您可以使用 shell 内置的参数替换来完成整个事情:
$ cat x.sh
filepath="/home/msubra/WORK/tmo/LOG/BCH1043.9987.log"
# Strip off the path. Everything between and including the slashes.
filename=${filepath##/*/}
# Then strip off everything after and including the first dot.
part1=${filename%%.*}
echo $part1
$ ./x.sh
BCH1043
$
文件路径中的点也不会造成问题。
有关详细信息,请参阅此处的第 4.5.4 节:http://docstore.mik.ua/orelly/unix3/korn/ch04_05.htm
哦,抵制住变得狡猾并在一行中完成所有操作的诱惑。分成单独的组件更容易调试和维护,谁知道您可能也需要使用这些组件(路径和文件名的其余部分)。
关于linux - shell 脚本 : to print selected text in the string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26784285/