bash sh - 按分隔符拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19930823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sh - split string by delimiter
提问by clarkk
code
代码
s='id;some text here with possible ; inside'
IFS=';' read -r id string <<< "$s"
echo "$id"
error
错误
restore.sh: 2: restore.sh: Syntax error: redirection unexpected
bash version GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)
bash 版本 GNU bash, version 4.2.37(1)-release (x86_64-pc-linux-gnu)
回答by chepner
A here string is just a shortcut for a small here document. This should work in any POSIX shell:
here 字符串只是一个小的 here 文档的快捷方式。这应该适用于任何 POSIX shell:
s='id;some text here with possible ; inside'
IFS=';' read -r id string <<EOF
$s
EOF
echo "$id"
回答by devnull
You seem to be using sh
to execute the script. Herestrings aren't supported in sh
; hence the error.
您似乎正在使用sh
来执行脚本。不支持这里字符串sh
;因此错误。
Ensure that you're using bash
to execute the script.
确保您正在使用bash
来执行脚本。
回答by Boris Urmantsev
save it in file split
将其保存在文件拆分中
#!/bin/sh
string=
c=0
while [ $c -le ]
do
val1=`echo "$string" |sed 's/\(^[^'']*\)\(''\+\)\(.*$\)//'`
string=`echo "$string" |sed 's/\(^[^'']*\)\(''\+\)\(.*$\)//'`
if [ "$val1" == "$string" ]
then
string=''
fi
if [ "$val1" == "" ]
then
let c=
fi
let c=c+1
done
echo $val1
and it work:
它的工作原理:
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
回答by alacerda
My result:
我的结果:
[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"
Worked here.
在这里工作。
回答by Michael Kazarian
I have used python2.7
below:
我在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 ''"
Result:
结果:
$ ./test.sh
id