bash SED:如何将字符串插入到最后一行的开头

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

SED: How to insert string to the beginning of the last line

linuxbashsedinsert

提问by Johann

How to insert string to the beginning of the last line?

如何将字符串插入到最后一行的开头?

I want to add a time stamp to a text file which contains multiple lines

我想向包含多行的文本文件添加时间戳

var1 = `date`

LINE1
LINE2
LINE3
...
(INSERT var1 here) LASTLINE

sed 's/^/test line /g' textfileinserts characters to the beginning of every line but how can I specifically modify the last line only?

sed 's/^/test line /g' textfile在每一行的开头插入字符,但我如何只修改最后一行?

Thanks

谢谢

Going forward: sed '$s/^/sample text /' textfileworks, but only when inserting regular strings. If I try

前进: sed '$s/^/sample text /' textfile有效,但仅在插入常规字符串时。如果我尝试

var1 = "sample text"

and use substition, here are the problems I encounter

并使用substition,这是我遇到的问题

  1. using single quotes in sed does not expand variables, so sed '$s/^/$var1/' textfile will insert the string $var1 into the beginning of the last line.

  2. To enable variable substitution I tried using double quotes. It works when I specify the exact line number. something like:

    sed "5s/^/$var1/" textfile

  1. 在 sed 中使用单引号不会扩展变量,因此 sed '$s/^/$var1/' 文本文件会将字符串 $var1 插入到最后一行的开头。

  2. 为了启用变量替换,我尝试使用双引号。当我指定确切的行号时它起作用。就像是:

    sed "5s/^/$var1/" 文本文件

But when I try sed "$s/^/$var1" text file, it returns an error:

但是当我尝试时sed "$s/^/$var1" text file,它返回一个错误:

sed: -e expression #1, char 5: extra characters after command

sed: -e 表达式 #1, char 5: 命令后的额外字符

Can someone help me please?

有人能帮助我吗?

回答by Guru

Like this:

像这样:

sed '$s/^/test line /' textfile

$indicates last line. Similarly, you can insert into a any specific line by putting the line number in place of $

$表示最后一行。同样,您可以通过将行号替换为任何特定行来插入$

回答by devnull

But when I try sed "$s/^/$var1" text file, it returns an error: 

It returns an error because the shellattempts to expand $ssince you've used double quotes. You need to escapethe $in $s.

它返回一个错误,因为shell尝试扩展,$s因为您使用了双引号。你需要逃避$$s

sed "$s/^/$var1/" filename

回答by Jotne

sedshould be the best tool, but awkcan do this too:

sed应该是最好的工具,但awk也可以这样做:

awk '{a[++t]=
awk 'NR==f {
sed -i "5s/^/$var1 /" text file
=v##代码##}1' v="$var1" f=$(wc -l file)
} END {for (i=1;i<t;i++) print a[i];print v##代码##}' v="$var1" file

It will insert value of var1in front of last line

它将var1在最后一行前面插入值



Another variation

另一种变体

##代码##

PS you do not need to specify file after awk, not sure why. If you do so, it reads it double.

PS 你不需要在 之后指定文件awk,不知道为什么。如果你这样做,它会读取双倍。

回答by Vivek Soni

This command would work for you:

这个命令对你有用:

##代码##