所以,我试图使用由“,”分隔的sed从字符串中提取多个值。
v = bsxfun(@times, 10:10:50, ones(10,1));
v = v(:).';
需要以下表达方面的帮助:
Working Eg:
Input :
echo "abc-de-aa-zzzz-1.2.3-4" | sed -E 's/(^([a-z]{3}-[a-z]{1,5}-[a-z]{1,5}-[a-z]{1,15})).*/\1/'
Output:
abc-de-aa-zzzz
谢谢,
杰森
答案 0 :(得分:2)
示例输入:
echo $x
abc-de-aa-zzzz-1.2.3-4,abc-de-aa-kkkk-1.2.5-4
awk
唯一的解决方案:
echo $x |awk 'BEGIN{RS=",";FS=OFS="-"}{NF=4}1'
abc-de-aa-zzzz
abc-de-aa-kkkk
或者,如果您希望输出以逗号分隔。 (最后一个额外的逗号)
echo $x |awk 'BEGIN{ORS=RS=",";FS=OFS="-"}{NF=4}1'
abc-de-aa-zzzz,abc-de-aa-kkkk,
使用tr
和awk
的脏解决方案
echo $x |tr ',' '\n' |awk -F'-' -v OFS='-' '{NF=4}1'
abc-de-aa-zzzz
abc-de-aa-kkkk
答案 1 :(得分:1)
可以使用纯Bash shell parameter expansion技术,但它涉及多级提取(两个),但不使用任何第三部分Linux工具,如awk
或sed
。您可以直接在命令行上运行它们。
# Read the input string into a bash array with a comma delimiter
$ IFS="," read -ra inputString <<< "abc-de-aa-zzzz-1.2.3-4,abc-de-aa-kkkk-1.2.5-4"
# For each of the individual strings, extract the sub-string from the end
# with de-limiter set as '-'
$ for eachString in "${inputString[@]}"; do tempString="${eachString%-*}"; \
tempString="${tempString%-*}"; printf "%s\n" "$tempString"; done
abc-de-aa-zzzz
abc-de-aa-kkkk
$
答案 2 :(得分:1)
一种方法是只删除不需要的字符串,在这种情况下,删除模式为-
,后跟3组数字,.
为分隔符,然后是最后的数字序列
$ echo "abc-de-aa-zzzz-1.2.3-4,abc-de-aa-kkkk-1.2.5-4" | sed -E 's/-([0-9]+\.){2}[0-9]+-[0-9]+//g'
abc-de-aa-zzzz,abc-de-aa-kkkk
替代解决方案: - 提取所需内容
使用grep
和pcre
$ echo "abc-de-aa-zzzz-1.2.3-4,abc-de-aa-kkkk-1.2.5-4" | grep -oP '(^|,)\K([^-]+\-){3}[^-]+'
abc-de-aa-zzzz
abc-de-aa-kkkk
使用GNU sed
$ echo "abc-de-aa-zzzz-1.2.3-4,abc-de-aa-kkkk-1.2.5-4" | sed 's/,/\n/' | sed -E 's/^(([^-]+\-){3}[^-]+).*/\1/'
abc-de-aa-zzzz
abc-de-aa-kkkk
如果您需要将输出组合为由,
$ echo "abc-de-aa-zzzz-1.2.3-4,abc-de-aa-kkkk-1.2.5-4" | grep -oP '(^|,)\K([^-]+\-){3}[^-]+' | paste -s -d,
abc-de-aa-zzzz,abc-de-aa-kkkk
答案 3 :(得分:1)
使用awk
:
awk -F, '{while(++i<=NF){sub(/-[0-9].*/,"",$i);print $i}}'
样品:
echo "abc-de-aa-zzzz-1.2.3-4,abc-de-aa-kkkk-1.2.5-4" | awk -F, '{while(++i<=NF){sub(/-[0-9].*/,"",$i);print $i}}'
abc-de-aa-zzzz
abc-de-aa-kkkk