gpt4 book ai didi

awk - 从一行中删除多个字符串

转载 作者:行者123 更新时间:2023-12-02 07:20:06 25 4
gpt4 key购买 nike

我有文本文件 bnglr.txt,其中包含以下 txt,我想根据我的要求删除某些字符串,确实我需要删除 |成功 | rc=0 | (stdout) # <- 每一行的一部分

# cat bnglr.txt
rraka-ged.rraka.com | SUCCESS | rc=0 | (stdout) # Profile host: trdls.rraka.com
rraka-avinashj.rraka.com | SUCCESS | rc=0 | (stdout) # Profile host: trdls.rraka.com

I have achieved this with awk and tr which returns the required, though i'm looking if this can be accomplished with awk itself without tr.. below is the result output what i received & desired

# awk '{gsub( /SUCCESS|rc=0|stdout/, "") ;a=$1;gsub($1 , "");print a,$0 }' bnglr.txt | tr -d "()|" | column -t 
rraka-ged.rraka.com # Profile host: trdls.rraka.com
rraka-avinashj.rraka.com # Profile host: trdls.rraka.com

Just edited the code ....

# awk '{print $1,$(NF-2)" "$(NF-1)" "$NF}' bnglr.txt | column -t
rraka-ged.rraka.com Profile host: trdls.rraka.com
rraka-avinashj.rraka.com Profile host: trdls.rraka.com

# awk '{print $1" ", substr($0,index($0,$9))}' bnglr.txt |column -t
rraka-ged.rraka.com Profile host: trdls.rraka.com
rraka-avinashj.rraka.com Profile host: trdls.rraka.com

即使使用 shell/awk 或 python,我也乐于看到任何解决方案..

最佳答案

|() 等字符在 ERE 中是元字符,因此您需要使用反斜杠对它们进行转义,使它们表现得像普通字符

对于给定的示例,您可以使用 sed 而不是默认使用 BRE,|() 并不特殊

另见 regex differences between different tools

$ sed 's/ | SUCCESS | rc=0 | (stdout)//' ip.txt | column -t
rraka-ged.rraka.com # Profile host: trdls.rraka.com
rraka-avinashj.rraka.com # Profile host: trdls.rraka.com


对于一般情况,我建议 perl Quoting metacharacters

$ # BRE metacharacters have to be taken care
$ echo '1a.c xabcy 2atc3' | sed 's/a.c//g'
1 xy 23
$ echo '1a.c xabcy 2atc3' | sed 's/a\.c//g'
1 xabcy 2atc3
$ # perl has \Q..\E feature to do that automatically
$ echo '1a.c xabcy 2atc3' | perl -pe 's/\Qa.c//g'
1 xabcy 2atc3

$ # but some characters are still special
$ echo '123a/b$c5467' | perl -pe 's|\Qa/b$c||'
123$c5467
$ # so, most robust solution is to pass the string as env string
$ echo '123a/b$c5467' | s='a/b$c' perl -pe 's/\Q$ENV{s}//'
1235467

关于awk - 从一行中删除多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48275106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com