如何删除仅在包含某些字符串的行之后加倍的行 - linux/bash
How to remove lines that are doubled only after line containing some string - linux/bash
如标题所述。我发现一个命令可以删除加倍的行:
perl -i.bak -ne 'print if ! $x{$_}++' ~/.bashrc
但是如何仅在包含特定字符串的行之后实现这一点,例如:
if line is after line with string "hello"
perl -i.bak -ne 'print if ! $x{$_}++' ~/.bashrc
我正在尝试使用 bash。
您可以使用范围提取运算符..
:
perl -i.bak -ne 'print if //../hello/ or !$x{$_}++' ~/.bashrc
有了 Ed,这很容易。我还在我的所有文件名中添加了一个“+”号,作为文件名和扩展名之间的记录分隔符,因此我可以使用 Cut 轻松地将它们分开,但如果你愿意,你可以删除它们。
文件+.txt:-
hi
hello
hello
there
脚本+.sh:-
#!/bin/sh -x
init () {
cat > edcommands+.txt << EOF
/hello/d
wq
EOF
next
}
end () {
rm ./edcommands+.txt
exit 0
}
next () {
[[ -z $(echo $edresult | grep '?') ]] && main
end
}
main () {
edresult=$(ed -s file+.txt < edcommands+.txt)
next
}
init
如标题所述。我发现一个命令可以删除加倍的行:
perl -i.bak -ne 'print if ! $x{$_}++' ~/.bashrc
但是如何仅在包含特定字符串的行之后实现这一点,例如:
if line is after line with string "hello"
perl -i.bak -ne 'print if ! $x{$_}++' ~/.bashrc
我正在尝试使用 bash。
您可以使用范围提取运算符..
:
perl -i.bak -ne 'print if //../hello/ or !$x{$_}++' ~/.bashrc
有了 Ed,这很容易。我还在我的所有文件名中添加了一个“+”号,作为文件名和扩展名之间的记录分隔符,因此我可以使用 Cut 轻松地将它们分开,但如果你愿意,你可以删除它们。
文件+.txt:-
hi
hello
hello
there
脚本+.sh:-
#!/bin/sh -x
init () {
cat > edcommands+.txt << EOF
/hello/d
wq
EOF
next
}
end () {
rm ./edcommands+.txt
exit 0
}
next () {
[[ -z $(echo $edresult | grep '?') ]] && main
end
}
main () {
edresult=$(ed -s file+.txt < edcommands+.txt)
next
}
init