Linux 使用 bash 删除文件每一行开头的空格

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

Delete whitespace in each begin of line of file, using bash

linuxbashwhitespace

提问by G-71

How i can delete whitespace in each line of file, using bash For instance, file1.txt. Before:

我如何使用 bash 删除文件每一行中的空格 例如,file1.txt。前:

  gg g
 gg g
t  ttt

after:

后:

gg g
gg g
t  ttt

采纳答案by Scharron

sed -i 's/ //g' your_filewill do it, modifying the file inplace.

sed -i 's/ //g' your_file会这样做,就地修改文件。

To delete only the whitespaces at the beginning of one single line, use sed -i 's/^ *//' your_file

要仅删除一行开头的空格,请使用 sed -i 's/^ *//' your_file

In the first expression, we replace all spaces with nothing. In the second one, we replace at the beginning using the ^keyword

在第一个表达式中,我们用空替换所有空格。在第二个中,我们使用^关键字替换开头

回答by kev

tr(delete all whitespaces):

tr(删除所有空格):

$ tr -d ' ' <input.txt >output.txt
$ mv output.txt input.txt

sed(delete leading whitespaces)

sed(删除前导空格)

$ sed -i 's/^ *//' input.txt

回答by Vijay

use can use perl -i for in place replacement.

使用可以使用 perl -i 进行就地替换。

perl -p -e 's/^ *//' file 

回答by Sopan Kurkute

To delete the white spaces before start of the line if the pattern matches. Use the following command. For example your foo.in has pattern like this

如果模式匹配,则删除行首之前的空格。使用以下命令。例如你的 foo.in 有这样的模式

      This is a test                                
                    Lolll
                       blaahhh
      This is a testtt

After issuing following command

发出以下命令后

sed -e '/This/s/ *//' < foo.in > foo.out

The foo.out will be

foo.out 将是

This is a test
             Lolll
                blaahhh
This is a testtt