string - Bash:字符串拆分问题
问题描述
我创建了以下代码:
function file_name {
if [ -n $1 ]; then
parts=$(echo -e $1 | tr "/")
for a in ${parts}; do
echo $a
done
fi
}
file_name("this_is/a_test/string")
当我运行它时,我收到以下错误:
./test: line 138: syntax error near unexpected token
`"this_is/a_test/string"'
./test: line 138: `file_name("this_is/a_test/string")'
解决方案
echo
没有,tr
和管道的纯 bash 版本。
可以很好地处理包含空格的文件名。
#! /bin/bash
function file_name {
local str="$1"
local token=
while [[ "${str}" =~ / ]]; do
token="${str%%/*}"
#if [[ "${token}" != "" ]]; then
echo "${token}"
#fi
str="${str#*/}"
done
if [[ -n "${str}" ]]; then
echo "${str}"
fi
}
file_name "this_is/a_test/string"
评论:
- 取消注释
if [[ "${token}" != "" ]]; then
,fi
如果您想压缩由双斜杠 (//
) 或以斜杠开头的路径引起的空名称
推荐阅读
- rest - 有没有办法通过 XtremIO 上的 REST 收集以下内容
- android - JNI_OnLoad() 中的 GetEnv 出现错误,删除这些行时应用程序崩溃,错误消失
- ios - 如何在 swift 5 中从 viewmodel 调用 ViewController 中的方法?
- python - AttributeError:当模型为“模型”对象时没有属性“可训练变量”
- machine-learning - Sagemaker:每次我需要进行预测时都进行培训:我应该如何构建解决方案?
- firebase - 替代 Crashlytics `+ (CLSStackFrame *)stackFrameWithAddress:(NSUInteger)address`
- python - “元组”对象没有属性“cuda”
- pandas - 每个时间间隔拆分数据帧
- node.js - 树莓 BLE 加密/配对
- android - 用于recyclerView的适配器的Android独立viewModel