bash 在行尾添加 sed

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

Add at the end of the line with sed

bashsed

提问by Open the way

given a plain text document with several lines like:

给定一个包含几行的纯文本文档,例如:

c48 7.587 7.39
c49 7.508 7.345983
c50 5.8 7.543
c51 8.37454546 7.34

I need to add some info 2 spaces after the end of the line, so for each line I would get:

我需要在行尾添加一些信息 2 个空格,所以对于每一行我都会得到:

c48 7.587 7.39  def
c49 7.508 7.345983  def
c50 5.8 7.543  def
c51 8.37454546 7.34  def

I need to do this for thousands of files. I guess this is possible to do with sed, but do not know how to. Any hint? Could you also give me some link with a tutorial or table for this cases?

我需要为数千个文件执行此操作。我想这可能与 sed 有关,但不知道如何操作。任何提示?你还可以给我一些关于这种情况的教程或表格的链接吗?

Thanks

谢谢

回答by ghostdog74

if all your files are in one directory

如果所有文件都在一个目录中

sed -i.bak 's/$/  def/' *.txt

to do it recursive (GNU find)

递归执行(GNU find)

find /path -type f -iname '*.txt' -exec sed -i.bak 's/$/  def/' "{}" +;

you can see herefor introduction to sed

你可以在这里看到sed 的介绍

Other ways you can use,

您可以使用的其他方式,

awk

awk

for file in *
do
  awk '{print 
for file in *
do
  while read -r line
  do
      echo "$line def"
  done < $file >temp
  mv temp $file
done
" def"}' $file >temp mv temp "$file" done

Bash shell

Bash 外壳

for file in ${thousands_of_files} ; do
    sed -i ".bak" -e "s/$/  def/" file
done

回答by Chen Levy

##代码##

The key here is the search-and-replace s///command. Here we replace the end of the line $with 2 spaces and your string.

这里的关键是搜索和替换s///命令。在这里,我们将行尾替换为$2 个空格和您的字符串。

Find the sed documentation at http://sed.sourceforge.net/#docs

http://sed.sourceforge.net/#docs 上找到 sed 文档