【问题标题】:Bash: String spliting issueBash:字符串拆分问题
【发布时间】:2021-10-23 17:55:11
【问题描述】:

我创建了以下代码:

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")'

【问题讨论】:

  • 括号用于创建子shell。
  • 删除括号后,通过shellcheck.net 运行脚本以进行其他有用的更正。

标签: string bash split


【解决方案1】:
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"

# writes:
# this_is                                                                                                  
# a_test                                                                                                   
# string 

您的代码中有两个问题。第一个是您现在在错误消息中看到的内容。原因是没有正确调用该函数。 Bash 处理像迷你脚本这样的函数,因此将参数传递给函数的语法就像你将参数传递给脚本一样。

更正后您将看到的第二个错误是tr 缺少参数。我假设您想将 / 替换为空格,以便 for 循环稍后正常工作。

【讨论】:

    【解决方案2】:
    1. bash 函数调用不需要()
    2. tr 需要第二个参数 tr "/" " "

    由于您没有任何空格,我建议使用命令替换来拆分字符串:

    function file_name {
        if [ -n $1 ]; then
            for part in ${1//\// } ; do 
                echo "$part"
            done
        fi
    }
    
    file_name "this_is/a_test/string"
    
    this_is
    a_test
    string
    

    Try it online!

    【讨论】:

      【解决方案3】:

      没有echotr 和管道的纯 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

      【讨论】:

        猜你喜欢
        • 2013-01-15
        • 1970-01-01
        • 1970-01-01
        • 2011-10-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多