从linux中的行尾删除空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20521857/
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-08-07 01:36:34  来源:igfitidea点击:

remove white space from the end of line in linux

linuxsed

提问by aksg24

i have file in which i want to remove white space from the end of line test.txt is as following (there is white space at the end of line.

我有我想从行尾删除空格的文件 test.txt 如下(行尾有空格。

ath-miRf10005-akr 
ath-miRf10018-akr 
ath-miRf10019-akr
ath-miRf10020-akr 
ath-miRf10023-akr
ath-miRf10024-akr 

i used sed 's/$\s//'but it is not working.

我用过,sed 's/$\s//'但它不工作。

采纳答案by fedorqui 'SO stop harming'

Use either a simple blank *or [:blank:]*to remove all possible spaces at the end of the line:

使用简单的空格*[:blank:]*删除行尾所有可能的空格:

sed 's/ *$//' file

Using the [:blank:]class you are removing spaces and tabs:

使用[:blank:]要删除空格和制表符的类:

sed 's/[[:blank:]]*$//' file

Note this is POSIX, hence compatible in both GNU sed and BSD.

请注意,这是 POSIX,因此在 GNU sed 和 BSD 中都兼容。

For just GNU sed you can use the GNU extension \s*to match spaces and tabs, as described in BaBL86's answer. See POSIX specifications on Basic Regular Expressions.

对于 GNU sed,您可以使用 GNU 扩展\s*来匹配空格和制表符,如BaBL86 的回答中所述。请参阅有关基本正则表达式的POSIX 规范。



Let's test it with a simple file consisting on just lines, two with just spaces and the last one also with tabs:

让我们用一个只包含行的简单文件来测试它,其中两个只有空格,最后一个也有制表符:

$ cat -vet file
hello   $
bye   $
ha^I  $     # there is a tab here

Remove just spaces:

只删除空格:

$ sed 's/ *$//' file | cat -vet -
hello$
bye$
ha^I$       # tab is still here!

Remove spaces and tabs:

删除空格和制表符:

$ sed 's/[[:blank:]]*$//' file | cat -vet -
hello$
bye$
ha$         # tab was removed!

回答by BaBL86

Try this:

尝试这个:

sed -i 's/\s*$//' youfile.txt

回答by NeronLeVelu

sed -i 's/[[:blank:]]\{1,\}$//' YourFile

[:blank:] is for space, tab mainly and {1,} to exclude 'no space at the end' of the substitution process (no big significant impact if line are short and file are small)

[:blank:] 用于空格,主要是制表符,{1,} 用于排除替换过程的“末尾没有空格”(如果行短且文件小,则没有太大的显着影响)

回答by iruvar

If your lines are exactly the way you depict them(no leading or embedded spaces), the following should serve as well

如果您的线条与您描绘它们的方式完全相同(没有前导或嵌入空格),则以下内容也应适用

awk '{=;print}' file.txt

回答by potong

This might work for you (GNU sed):

这可能对你有用(GNU sed):

sed -ri  '/\s+$/s///' file

This looks for whitespace at the end of the line and and if present removes it.

这会在行尾查找空格,如果存在则将其删除。

回答by Kamal

Try using

尝试使用

cat kb.txt | sed -e 's/\s$//g'