我有一个文件f1,其中包含以下数据:
---
sc_swVersion_t isaPDAVersion = {0,4,0,0,0,34};
---
我想从中提取大括号后面的前4个字符。有人能告诉我们什么unix实用程序/shell命令可以做到这一点吗。说:
cat f1 | grep isaPDAVersion | < Some utility> gives me 0400
grep isaPDAVersion f1 | awk -F{ '{print $2}'| awk -F, '{print $1$2$3$4}'
或者更简单地说,在目瞪口呆的中
gawk '/isaPDAVersion/ {match($4,"([[:digit:]]),([[:digit:]]),([[:digit:]]),([[:digit:]])",a); {print a[1]a[2]a[3]a[4]}}' f1
您可以使用sed完成所有操作,例如
cat f1 | sed -ne "s/^.*isaPDAVersion[^{]*{([^,]*,[^,]*,[^,]*,[^,]*).*$/1/p"
sed 's/[^{]*{//; # discard up to and including the first {
s/,//g; # discard the commas
s/(....).*/1/ # get the first four characters, discard the rest
'
简短回答:
echo "sc_swVersion_t isaPDAVersion = {0,4,0,0,0,34};" | cut -f2 -d{ | cut -f1-4 -d, | tr -d ,
用"cat文件名"和voila替换echo。
真恶心。只需使用Perl。
perl -nE's/D//g,print for@{[split/,/]}[0..3]'
^无需滚动。
您可以使用sed
:
sed -n '/{/s/^.*{([0-9]*),([0-9]*),([0-9]*),([0-9]*).*$/1234/p' f1
GNU awk
gawk '
match($0, /isaPDAVersion.*{([^,]+),([^,]+),([^,]+),([^,]+),/, a) {
printf("%s%s%s%sn", a[1], a[2], a[3], a[4])
}
' f1