bash 如何删除文件最后一行的最后一个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33680111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:54:04  来源:igfitidea点击:

How can I remove the last character of the last line of a file?

linuxbashfile

提问by Joan Triay

I have this set of lines in a file:

我在文件中有这组行:

{info},
{info},
{info},
{info},

and I want the file like this without the last ",":

我想要这样的文件,没有最后一个“,”:

{info},
{info},
{info},
{info}

How can I do it in bash? Any idea?

我怎样才能在 bash 中做到这一点?任何的想法?

回答by Maroun

You can use sed:

您可以使用sed

sed '$ s/.$//' your_file
  • First $is to tell sedto match only last line
  • sis for "substitute", note the empty string between the two last /s
  • .$is a regex that matches the last character in the file
  • 首先$是告诉sed只匹配最后一行
  • s用于“替换”,请注意最后两个/s之间的空字符串
  • .$是匹配文件中最后一个字符的正则表达式

Note that you can use whatever separator you want instead of /, for example you can rewrite the expression:

请注意,您可以使用任何您想要的分隔符来代替/,例如您可以重写表达式:

sed '$ s-.$--' your_file

回答by Lando

In vim, you could use :substitute or :s to do this as well. It's a vim-built in -- you can read about it here http://vim.wikia.com/wiki/Search_and_replace

在 vim 中,您也可以使用 :substitute 或 :s 来执行此操作。这是一个内置的 vim——你可以在这里阅读它 http://vim.wikia.com/wiki/Search_and_replace

The syntax is very similar to the other posted solution, you'd go into the command mode and type in :$s/.$//g

语法与其他发布的解决方案非常相似,您将进入命令模式并输入 :$s/.$//g