在文本文件中的每一行前添加 ##

Oxw*_*ivi 31 text-processing

我想向常规文本文件中的所有行添加哈希。我对终端和 GUI 的使用都很好——我只需要完成它。

Juk*_*nen 53

你可以sed用来做到这一点:

sed -i.bak 's/^/##/' file
Run Code Online (Sandbox Code Playgroud)

这将行 ( ^)的开头替换为##

使用-i.bak开关,sed就地编辑文件,但创建扩展名为.bak.


小智 8

这是使用 perl 解决此问题的方法

perl -e 'while (<>) {print "##$_"}' < infile > outfile
Run Code Online (Sandbox Code Playgroud)

  • `-p` 开关也很有用:`perl -pe 's/^/##/' infile &gt; outfile`。(还有用于就地替换目标文件的 `-i[extension]` 开关。)http://perldoc.perl.org/perlrun.html#%2a-p%2a (2认同)

mur*_*uru 7

当我们在做的时候:

gawk -i inplace '{print "##"$0}' infile
Run Code Online (Sandbox Code Playgroud)

这使用了GNU awk 4.1.0+的(相对较新的)就地编辑插件


Eli*_*gan 5

这里有一个bash方法:

while read -r; do printf '##%s\n' "$REPLY"; done < infile > outfile
Run Code Online (Sandbox Code Playgroud)

bashshell 中,在read -r没有其他参数的情况下运行就像IFS= read -r REPLY。)

这在风格上受到beav_35 的 perl 解决方案的启发,我承认它对于大文件可能运行得更快,因为perl在文本处理方面可能比 shell 更有效。