从文件中删除最后一次出现} [英] remove the last occurrence of } from a file
问题描述
我试图使用sed从文件中删除最后一次出现}。到目前为止,我有这样的:
I'm trying to use sed to remove the last occurrence of } from a file. So far I have this:
sed -i 's/\(.*\)}/\1/' file
但是,这消除多达}因为有上的文件的末尾。所以,如果我的文件看起来像这样:
But this removes as many } as there are on the end of the file. So if my file looks like this:
foo
bar
}
}
}
该命令将删除}个字符的所有3。如何限制这刚刚过去的发生?
that command will remove all 3 of the } characters. How can I limit this to just the last occurrence?
推荐答案
是在一行简单的替换一个很好的工具。为别的,只用awk,例如与GNU AWK为gensub()和多字符RS:
sed is an excellent tool for simple substitutions on a single line. For anything else, just use awk, e.g. with GNU awk for gensub() and multi-char RS:
$ cat file1
foo
bar
}
}
}
$
$ cat file2
foo
bar
}}}
$
gawk -v RS='^$' -v ORS= '{$0=gensub(/\n?}([^}]*)$/,"\\1","")}1' file1
foo
bar
}
}
$
$ gawk -v RS='^$' -v ORS= '{$0=gensub(/\n?}([^}]*)$/,"\\1","")}1' file2
foo
bar
}}
$
请注意,上面会删除最后一个}字符和一个preceding换行,如果present因为我认为这可能是你真正想要的,但如果你希望只删除}
,并留下一个尾随的换行符在这些情况下(因为我觉得所有当前发布的 SED
解决方案会做),那么刚刚摆脱<$的C $ C> \\ n 从匹配RE:
Note that the above will remove the last } char AND a preceding newline if present as I THINK that's probably what you would actually want but if you want to ONLY remove the }
and leave a trailing newline in those cases (as I think all of the currently posted sed
solutions would do), then just get rid of \n?
from the matching RE:
$ gawk -v RS='^$' -v ORS= '{$0=gensub(/}([^}]*)$/,"\\1","")}1' file1
foo
bar
}
}
$
如果你想改变原有的文件,而无需手动指定tmp文件,只需要使用 -i就地
参数:
$ gawk -i inplace -v RS='^$' -v ORS= '{$0=gensub(/}([^}]*)$/,"\\1","")}1' file1
$ cat file1
foo
bar
}
}
$
这篇关于从文件中删除最后一次出现}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!