[英]How to replace a pattern from a TSV using sed?
我有一個TSV文件,其中char *用作空標識符,我想刪除它,該文件如下所示:
Foo Foo foo FOO
Bar * * *
*Bar Foo* Foo * Bar Foo bar
* * Bar Foobar
如果我使用s/(^| )\\*( |$)/\\1\\2/g
給出此輸出:
Foo Foo foo FOO
Bar *
*Bar Foo* Foo * Bar Foo bar
* Bar Foobar
如果一個是,另一個不是,如果它們都被TABS包圍,我該怎么辦才能替換掉它們?
所需的輸出應如下所示:
Foo Foo foo FOO
Bar
*Bar Foo* Foo * Bar Foo bar
Bar Foobar
由於尚不清楚選項卡是什么,所以讓我們嘗試一下|
作為字段分隔符:
$ cat a
Foo|Foo|foo|FOO
Bar|*|*|*
*Bar|Foo*|Foo * Bar|Foo bar
*|*|Bar|Foobar
因此,使用awk
我們可以做到:
$ awk 'BEGIN{FS=OFS="|"}{for (i=1; i<=NF; i++) if ($i=="*") $i=""}1' a
Foo|Foo|foo|FOO
Bar|||
*Bar|Foo*|Foo * Bar|Foo bar
||Bar|Foobar
如果它們的值正好是*
它將遍歷所有字段並將其空白(將它們設置為空)。
注意:要使此解決方案與示例輸入配合使用,只需替換字段分隔符的定義:從BEGIN{FS=OFS="|"}
到BEGIN{FS=OFS="\\t"}
。
您可以嘗試下面的perl逗號,
$ perl -pe 's/(\W|^)\*\t\*/\1/g;s/\t\*$//g' file
Foo Foo foo FOO
Bar
*Bar Foo* Foo * Bar Foo bar
Bar Foobar
授予它們制表符分隔的位置:
sed -r 's@([^\t])[*]@\1__0x2A__@g; s@[*]([^\t\r])@__0x2A__\1@g; s@[*]@@g; s@__0x2A__@*@g' file
更短:
sed -r 's@([^\t])[*]@\1\a@g; s@[*]([^\t\r])@\a\1@g; s@[*]@@g; s@\a@*@g' file
輸出:
Foo Foo foo FOO
Bar
*Bar Foo* Foo * Bar Foo bar
Bar Foobar
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.