原始文件
123|abc|heloo good morning friends|1|123|abc|123|abc
123|abc|heloo good morning everyone|1|123|abc|123|abc
替换的文件
123|abc|heloo good morning freinds|1|123|abc|123|abc
123|abc|this is what i want to see|1|123|abc|123|abc
正如您所看到的,分隔符是|
。现在,如果任何块包含单词“每个人”,则该特定块应该更改为“这就是我想看到的”。
答案1
只需循环遍历字段并检查它们是否匹配:
awk 'BEGIN{FS=OFS="|"}
{for (i=1; i<=NF; i++)
if ($i ~ "everyone") $i="this is what i want to see"
print}' file
查看输出:
$ awk 'BEGIN{FS=OFS="|"} {for (i=1; i<=NF; i++) if ($i ~ "everyone") $i="this is what i want to see"; print}' file
123|abc|heloo good morning friends|1|123|abc|123|abc
123|abc|this is what i want to see|1|123|abc|123|abc
以更惯用的方式,if
条件可以写为($i ~ "everyone") && $i="this is what i want to see"
然后只使用 true 条件来打印行:
awk 'BEGIN{FS=OFS="|"} {for (i=1; i<=NF; i++) ($i ~ "everyone") && $i="this is what i want to see"} 1' file
答案2
sed 's/[^|]*everyone[^|]*/this is what I want to see/g' <<\DATA
123|abc|heloo good morning friends|1|123|abc|123|abc
123|abc|heloo good morning everyone|1|123|abc|123|abc
DATA
输出
123|abc|heloo good morning friends|1|123|abc|123|abc
123|abc|this is what I want to see|1|123|abc|123|abc
这匹配任何出现的每个人以及其左侧或右侧的整个序列,但不包括分隔符|。所以上面的方法有效。但也是如此:
sed 's/[^|]*everyone[^|]*/replace/g' <<\DATA
everyone|everyevery|every|one|
everyone|everyone|heloo good morning everyone|everyone|123|abc|123|abc
DATA
输出
replace|everyevery|every|one|
replace|replace|replace|replace|123|abc|123|abc