简体   繁体   English

Sed / Grep-过滤出内容

[英]Sed/Grep - Filter Out Content

Given that I have something like this: 鉴于我有这样的事情:

int val; struct node *mhm;
int val; struct node *next;

I want to extract content on each line, using sed, awk, or grep so that they read: 我想使用sed,awk或grep提取每一行的内容,以便它们读取:

init->val = val; init->mhm = mhm;
init->val = val; init->next = next;

grep -o outputs each individual result on a new line, but I need to preserve line structure (each group of variables refer to a separate thing). grep -o在换行符上输出每个单独的结果,但是我需要保留行结构(每组变量都引用一个单独的东西)。

I use a gnu sed command presently, but I only want to output the replaced string: 我现在使用gnu sed命令,但是我只想输出替换后的字符串:

sed -re 's/([A-Za-z0-9_]*);/init->\1 = \1;/g'

This above sed command outputs: 上面的sed命令输出:

int init->val = val; struct node *init->mhm = mhm;
int init->val = val; struct node *init->next = next;

Even when using non-greedy modifiers, I can't get a full line regex statement to successfully select each variable name in each line. 即使使用非贪婪修饰符,我也无法获得完整的正则表达式语句来成功选择每一行中的每个变量名称。

这适用于您的样本集(对解决方案进行了微小更改):

sed -re 's/[^;]* [*]?([A-Za-z0-9_]+) *;/init->\1 = \1; /g'

There isin't a variable name in each line unless you parse the language. 除非您解析语言,否则每行中都没有变量名。

That being said, as just random text, this: 话虽如此,只是随机文本,这是:
s/([^\\S\\n]*)[^;\\n]+?(\\w+)\\s*;/\\1init->\\2 = \\2;/g
should do it. 应该这样做。

尝试这个

awk '{for(i=1;i<=NF;i++) if($i~/;/){ gsub(/\*/,"",$i);a=gensub(/(\w*);/, "init->\\1 = \\1; ","g",$i);printf a;}print ""}' yourFile

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

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