2

代码

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

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

4

5 回答 5

11

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

s='id;some text here with possible ; inside'
IFS=';' read -r id string <<EOF
$s
EOF
echo "$id"
于 2013-11-12T14:38:23.757 回答
6

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

确保您bash用于执行脚本。

于 2013-11-12T13:48:10.740 回答
1

将其保存在文件拆分中

#!/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
于 2018-08-18T14:19:10.277 回答
0

我的结果:

[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"

在这里工作。

于 2013-11-12T14:40:52.327 回答
-1

我在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-11-12T14:34:41.230 回答