首页 > 解决方案 > 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")'

标签: stringbashsplit

解决方案


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}" != "" ]]; thenfi如果您想压缩由双斜杠 ( //) 或以斜杠开头的路径引起的空名称

推荐阅读