如何删除具有特定字符串的所有行但不删除同一文件的特定部分中包含相同字符串的行

how to delete all lines with a particular string but not deleting the lines containing the same string in a particular section of the same file

文件包含以下行:

UserName aashii
UserName drisha
UserName aashii
UserName harsha
UserName sampada
<Anonymous>
UserName drisha
UserName aashii
</Anonymous>

我想从 unix 文件中删除字符串 "UserName aashii" 的行,而不删除 <Anonymous>....</Anonymous>.

部分下字符串 "UserName aashii" 的行

我试过命令:

sed -i '/^ *UserName *aashii *$/d' -i $file

但是它删除了所有包含该字符串的行,甚至是 <Anonymous>.....</Anonymous>

部分下包含该字符串的行

你可以说:

awk '/<Anonymous>/,/<\/Anonymous>/ {print;next} !/UserName aashii/' file

哪个returns:

UserName drisha
UserName harsha
UserName sampada
<Anonymous>
UserName drisha
UserName aashii
</Anonymous>

也就是说,如果它是 range expression 的一部分或不包含 "UserName aashii".

,则打印

使用 GNU sed:

sed -n '/<Anonymous>/,/<\/Anonymous>/{p;b};/UserName aashii/d;p' file

输出:

UserName drisha
UserName harsha
UserName sampada
<Anonymous>
UserName drisha
UserName aashii
</Anonymous>

-n: suppress automatic printing of pattern space

/<Anonymous>/,/<\/Anonymous>/{p;b}: in the complete range from matching line <Anonymous> to </Anonymous> print pattern space (p) and then jump to end of script (b) (no further processing of other commands).

/UserName aashii/d: for lines matching UserName aashii delete pattern space (d) and start next cycle (no further processing of other commands).

p: print pattern space