繁体   English   中英

哪个 unix 实用程序可以帮助我从文件中的一行中提取特定字符

[英]Which unix utility can help me extract specific characters from a line in the file

我有一个包含以下数据的文件 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

呸。 只需使用 Perl。

perl -nE's/\D//g,print for@{[split/,/]}[0..3]'

^ 无需滚动。

您可以使用 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 ,

将 echo 替换为“cat 文件名”,瞧。

你可以用sed做到这一点:

sed -n '/{/s/^.*{\([0-9]*\),\([0-9]*\),\([0-9]*\),\([0-9]*\).*$/\1\2\3\4/p' f1

GNU awk

gawk '
  match($0, /isaPDAVersion.*\{([^,]+),([^,]+),([^,]+),([^,]+),/, a) {
    printf("%s%s%s%s\n", a[1], a[2], a[3], a[4])
  }
' f1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM