【问题标题】:sh - split string by delimitersh - 按分隔符分割字符串
【发布时间】:2013-11-24 16:46:45
【问题描述】:

代码

s='id;some text here with possible ; inside'
IFS=';' read -r id string <<< "$s"
echo "$id"

错误

restore.sh: 2: restore.sh: Syntax error: redirection unexpected

bash 版本GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)

【问题讨论】:

  • 在GNU bash, version 4.2.45(1)-release (x86_64-pc-linux-gnu)上为我工作

标签: linux bash sh herestring


【解决方案1】:

here 字符串只是小here 文档的快捷方式。这应该适用于任何 POSIX shell:

s='id;some text here with possible ; inside'
IFS=';' read -r id string <<EOF
$s
EOF
echo "$id"

【讨论】:

  • 我是 shell 新手,但来自 Java 背景。你能解释一下你的代码吗?
  • @Jess:很晚的评论,但无论如何,我的两分钱:POSIX read 期望标准输入上有一行,读取它并使用 $IFS 内容作为分隔符将其拆分,然后将每个块分配给作为read 的参数给出的变量(id 和string;id 获得第一个块,string 获得所有剩余的块)。这两个 EOF 的技巧称为“heredoc”,AFAIK 是将该字符串发送到read 的标准输入的唯一方法。另请参阅pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html。
【解决方案2】:

您似乎正在使用sh 执行脚本。 sh 不支持这里的字符串;因此错误。

确保您使用bash 执行脚本。

【讨论】:

  • sh 和 bash 有什么区别?
  • 一些 Linux 发行版使用dash(不是bash)作为实现sh 的shell。 dash (大部分?)仅限于 POSIX 规范指定的功能,没有 bash 实现的 &lt;&lt;&lt; 等额外功能。
  • 这工作 echo "$s" | cut -d";" -f1 但我怎样才能将它分配给一个变量?
  • @clarkk:使用var=$(echo "$s" | cut -d";" -f1)
【解决方案3】:

将其保存在文件拆分中

#!/bin/sh

string=$1
c=0

while [ $c -le $3 ] 
do

val1=`echo "$string" |sed 's/\(^[^'$2']*\)\('$2'\+\)\(.*$\)/\1/'`
string=`echo "$string" |sed 's/\(^[^'$2']*\)\('$2'\+\)\(.*$\)/\3/'`

if [ "$val1" == "$string" ]
then
string=''
fi

if [ "$val1" == "" ]
then
let c=$3
fi

let c=c+1

done

echo $val1 

它的工作原理:

root@IPHONE:~# ./split 'a;b;c' ';' 0
a
root@IPHONE:~# ./split 'a/b/c' '\/' 0
a
root@IPHONE:~# ./split 'a/b/c' '\/' 2
c
root@IPHONE:~# ./split 'a/b/c' '\/' 1
b

【讨论】:

    【解决方案4】:

    我的结果:

    [root@localhost ~]# bash --version
    GNU bash, version 3.2.25(1)-release (i686-redhat-linux-gnu)
    Copyright (C) 2005 Free Software Foundation, Inc.
    [root@localhost ~]# ./bash
    id
    [root@localhost ~]# cat bash
    s='id;some text here with possible ; inside'
    IFS=';' read -r id string <<< "$s"
    echo "$id"
    

    在这里工作。

    【讨论】:

      【解决方案5】:

      我在下面使用过python2.7:

      #!/bin/sh
      
      s='id;some text here with possible ; inside'
      python -c "ifc, s =';', '$s';print s.split(';')[0] if ifc in s else ''"
      

      结果:

       $ ./test.sh
      id
      

      【讨论】:

        猜你喜欢
        • 2013-05-03
        • 2021-06-12
        • 2017-03-25
        • 2012-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多