如何在:
之前提取所有字符串,我只能得到第一个
$ echo "cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee" | sed 's/:.*//g'
$ cc_dd
# want to print cc_dd aa_bb and ee_ff
答案 0 :(得分:2)
短 grep 方法:
s="cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee"
grep -Po '[^;:]+(?=:)' <<< $s
-P
选项,允许Perl正则表达式
-o
选项,告诉只打印匹配的子字符串
(?=:)
- 积极的先行断言,确保所需的子字符串后跟:
输出:
cc_dd
aa_bb
ee_ff
效果比较:
time (for i in {1..1000}; do grep -Po '[^;:]+(?=:)' <<< $s > /dev/null; done;)
real 0m1.936s
user 0m0.036s
sys 0m0.236s
time (for i in {1..1000}; do awk -v RS=\; '{split($0,a,":"); print a[1]}' <<< $s > /dev/null; done;)
real 0m2.633s
user 0m0.056s
sys 0m0.264s
答案 1 :(得分:2)
awk
救援!
echo "cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee" |
awk -v RS=\; '{split($0,a,":"); print a[1]}'
cc_dd
aa_bb
ee_ff
答案 2 :(得分:0)
awk -F'[;:]' '{print $1,$3,$5}' OFS='\n' file
cc_dd
aa_bb
ee_ff