简体   繁体   English

sed将文件中的文本追加到行中

[英]sed append text from file onto line

I have some bash that calculates 90% of the total system memory in KB and outputs this into a file: 我有一些bash可以计算系统总内存的90%(以KB为单位)并将其输出到文件中:

cat /proc/meminfo | grep MemTotal | cut -d: -f2 | awk '{SUM += $1} END { printf "%d", SUM/100*90}' | awk '{print $1}' > mem.txt

I then want to copy the value into another file (/tmp/limits.conf) and append to a single line. 然后,我想将该值复制到另一个文件(/tmp/limits.conf)中并追加到一行。

The below searches for the string "soft memlock" and writes the output of mem.txt created earlier into the /tmp/limistest.conf 下面搜索字符串“ soft memlock”,并将mem.txt创建的mem.txt的输出写入/tmp/limistest.conf

sed -i '/soft\smemlock/r mem.txt' /tmp/limitstest.conf

However the script outputs as below: 但是脚本输出如下:

oracle   soft memlock
1695949

I want it to output like this: 我希望它输出如下:

oracle   soft memlock 1695949

I have tried quite a few things but can't get this to output correctly. 我已经尝试了很多事情,但是无法正确输出。

Thanks 谢谢

Edit here is some of the text in input file /proc/meminfo 编辑这里是输入文件/ proc / meminfo中的一些文本

MemTotal:          18884388 kB
MemFree:            1601952 kB
MemAvailable:       1607620 kB

I think your approach is overly complicated: there is no need to store the output in a file and then append it into another file. 我认为您的方法过于复杂:无需将输出存储在文件中,然后将其附加到另一个文件中。

What if you just store the value in a variable and then add it into your file? 如果仅将值存储在变量中,然后将其添加到文件中怎么办?

var=$(command)
sed "/soft memlock/s/.*/& $var/" /tmp/limitstest.conf

Once you are confident with the output, add the -i in the sed operation. 对输出充满信心后,在sed操作中添加-i

Where, in fact, command can be something awk alone handles: 实际上, command可以单独由awk处理:

awk '/MemTotal/ {sum+=$2} END { printf "%d", SUM/100*90}' /proc/meminfo

See a test on the sed part: 查看sed部分的测试:

$ cat a
hello
oracle soft memlock
bye
$ var=2222
$ sed "/soft memlock/s/.*/& $var/" a
hello
oracle soft memlock 2222
bye

It's a bit of a guess since you didn't provide sample input/output but all you need is something like: 有点猜测,因为您没有提供示例输入/输出,但是您所需要的只是:

awk '
NR==FNR {
    if (/MemTotal/) {
        split($0,f,/:/)
        $0 = f[2]
        sum += $1
    }
    next
}
/soft[[:space:]]+memlock/ { $0 = $0 OFS int(sum/100*90) }
{ print }
' /proc/meminfo /tmp/limitstest.conf > tmp &&
mv tmp /tmp/limitstest.conf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM