This question already has an answer here:
这个问题在这里已有答案:
- How can I remove the last character of a file in unix? 8 answers
如何在unix中删除文件的最后一个字符? 8个答案
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做呢?任何的想法?
2 个解决方案
#1
11
You can use sed
:
你可以使用sed:
sed '$ s/.$//' your_file
- First
$
is to tellsed
to match only last line -
s
is for "substitute", note the empty string between the two last/
s -
.$
is a regex that matches the last character in the file
第一个$是告诉sed只匹配最后一行
s代表“替代”,注意两个最后/秒之间的空字符串
。$是与文件中最后一个字符匹配的正则表达式
Note that you can use whatever separator you want instead of /
, for example you can rewrite the expression:
请注意,您可以使用您想要的任何分隔符而不是/,例如,您可以重写表达式:
sed '$ s-.$--' your_file
#2
1
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
#1
11
You can use sed
:
你可以使用sed:
sed '$ s/.$//' your_file
- First
$
is to tellsed
to match only last line -
s
is for "substitute", note the empty string between the two last/
s -
.$
is a regex that matches the last character in the file
第一个$是告诉sed只匹配最后一行
s代表“替代”,注意两个最后/秒之间的空字符串
。$是与文件中最后一个字符匹配的正则表达式
Note that you can use whatever separator you want instead of /
, for example you can rewrite the expression:
请注意,您可以使用您想要的任何分隔符而不是/,例如,您可以重写表达式:
sed '$ s-.$--' your_file
#2
1
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