sh - split string by delimiter

若如初见. 提交于 2021-01-27 23:36:36

问题


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)


回答1:


You seem to be using sh to execute the script. Herestrings aren't supported in sh; hence the error.

Ensure that you're using bash to execute the script.




回答2:


A here string is just a shortcut for a small here document. This should work in any POSIX shell:

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



回答3:


save it in file split

#!/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 

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



回答4:


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.




回答5:


I have used python2.7 below:

#!/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


来源:https://stackoverflow.com/questions/19930823/sh-split-string-by-delimiter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!