得到两个字符和输出字段之间的字符串逗号作为分隔符
问题描述:
我有以下字符串:得到两个字符和输出字段之间的字符串逗号作为分隔符
":: +1 +2 +3 +4 +5 -7 -6 :: 7 cycles"
我想::
之间的grep一切,除去+
标志,并用逗号作为分隔符写数字,没有在开始或结束空格或逗号:
1,2,3,4,5,-7,-6
我曾尝试以下:
echo ":: +1 +2 +3 +4 +5 -7 -6 :: 7 cycles" | sed -e 's/.*::\(.*\)::.*/\1/' | sed -e 's/+//g' -e 's/ /,/g'
它还没有。问题是,虽然在这里我有7个字段(数字),但在我的工作中,字段数量可能会有所不同,因此我不能仅使用 awk语句打印字段。它需要一个适用于任何领域的解决方案。
答
通过使用::
使用awk
你可以做到容易地作为输入字段分隔符(由空间和/或加号包围):
s=":: +1 +2 +3 +4 +5 -7 -6 :: 7 cycles"
awk -F '[+ ]*::[ +]*' '{gsub(/[+ ]+/, ",", $2); print $2}' <<< "$s"
1,2,3,4,5,-7,-6
答
:
呆子溶液:
s=":: +1 +2 +3 +4 +5 -7 -6 :: 7 cycles"
awk -v FPAT="[+-][0-9]+" '{ r="";
for(i=1;i<=NF;i++){ gsub(/^+/,"",$i); r= (r)? r","$i : $i } print r}' <<< $s
FPAT="[+-][0-9]+"
- 表示字段val的模式ue(即与前述+
或-
)gsub(/^+/,"",$i)
一个数字 - 若干
sed的前去除可能+
方法:
sed 's/::\(.*\)::.*/\1/; s/ \([+-]\)/,\1/g; s/^,+\|+//g' <<< $s
1,2,3,4,5,-7,-6
-
s/::\(.*\)::.*/\1/
- 捕获一切::
输出(对于这两种方法)之间
:
1,2,3,4,5,-7,-6
答
随着perl
$ echo ':: +1 +2 +3 +4 +5 -7 -6 :: 7 cycles' |
perl -F:: -lane 'print join ",", $F[1] =~ /-?\d+/g'
1,2,3,4,5,-7,-6
-
-F::
设置::
作为字段分隔符,结果保存在@F
阵列 -
$F[1]
是@F
阵列的第二元素将包含+1 +2 +3 +4 +5 -7 -6
-
$F[1] =~ /-?\d+/g
将返回所有的数字与任选-
前缀 -
join ","
将增加所提取的字符串之间,
- 有关详细信息,请参见https://perldoc.perl.org/perlrun.html#Command-Switches
-lane
选项
答
Pure Bash:使用参数扩展(使用扩展小球):
# Turn on extglobs
shopt -s extglob
s=":: +1 +2 +3 +4 +5 -7 -6 :: 7 cycles"
# Remove leading colons (and spaces following them)
s1=${s##::*([[:space:]])}
# Remove trailing colons (and spaces leading them)
s2=${s1%%*([[:space:]])::*}
# Remove all + signs
s3=${s2//+}
# Replace all spaces by commas
s4=${s3//+([[:space:]])/,}
# Done
echo "$s4"
这很有趣。是否可以在同一命令中删除第一个和最后一个逗号?因此,只有1,2,3,4,5,-7,-6? – Homap
是的,现在查看我更新的答案。 – anubhava
为什么你有双星号? – 123