![](/img/trans.png)
[英]Split a string to print first two characters delimited by “-” In Bash
[英]Print out the string between first two “;” in Bash
我想知道如何獲取前兩個“;”之間的字符串。 在Bash中使用sed
例如:
輸入:
END; startprocess -noprint; CWD: 8995; RUID: nmsadm; EUID: nmsadm; ERRCODE: 0;
輸出:
startprocess -noprint
cut
救援:
cut -d';' -f2
$ cut -d';' -f2 <<< "END; startprocess -noprint; CWD: 8995; RUID: nmsadm; EUID: nmsadm; ERRCODE: 0;"
startprocess -noprint
cut
可能是這里最好的選擇,但這是一個如何在bash本身中完成此操作的示例
IFS=';' read -r _ var _ <<<
'END; startprocess -noprint; CWD: 8995; RUID: nmsadm; EUID: nmsadm; ERRCODE: 0;'
echo $var
sed
不是最好的解決方案,並且最好像fedorqui的回答中那樣使用cut
,但是如果您必須:
$ str='END; startprocess -noprint; CWD: 8995; RUID: nmsadm; EUID: nmsadm; ERRCODE: 0;'
$ echo "$str" | sed 's/^[^;]*;\([^;]*\);.*$/\1/'
startprocess -noprint
您實際上不需要調用任何外部實用程序。 這是純[tag_bash]的簡單解決方案:
x='END; startprocess -noprint; CWD: 8995; RUID: nmsadm; EUID: nmsadm; ERRCODE: 0;'
[[ $x =~ \;[^\;]+\; ]] && echo "${BASH_REMATCH:1:((${#BASH_REMATCH}-2))}"
輸出:
startprocess -noprint
或更簡單的一個:
x=${x#*;}; echo "${x%%;*}"
使用awk:
awk -F';' '{print $2}'
例:
$ str='END; startprocess -noprint; CWD: 8995; RUID: nmsadm; EUID: nmsadm; ERRCODE: 0;'
$ awk -F';' '{print $2}' <<< $str
startprocess -noprint
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.