senator404
senator404

Reputation: 15

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:

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.

The below searches for the string "soft memlock" and writes the output of mem.txt created earlier into the /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

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

Upvotes: 1

Views: 130

Answers (2)

fedorqui
fedorqui

Reputation: 289495

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.

Where, in fact, command can be something awk alone handles:

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

See a test on the sed part:

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

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203149

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

Upvotes: 1

Related Questions