khal-el
khal-el

Reputation: 39

How to insert a variable content using sed command

I have shell script (.sh) and I'm trying to insert contents of a file onto another file using the following commands but I it's throwing an error "sed: -e expression #1, char 28: unknown option to `s'":

filename="/home/user1/filename.txt"
contents=$(du -sh /var/log/test.log)
hostname > $filename
sed -i "/test_string/ s/$/, $contents" $filename

I can't seem to figure out where the underlying issue is. Can someone please help?

Example:

filename=/home/user1/filename.txt

hostname = server1.mydomain.com

So the content of $filename is server1.mydomain.com after running hostname > $filename.

The output of du -sh /var/log/test.log command is let say 1.3M /var/log/test.log

So running sed -i "/mydomain.com/ s/$/, $contents" $filename should update the content of the following filename to:

server1.mydomain.com, 1.3M /var/log/test.log

But as I mentioned above, it's throwing an error.

Upvotes: 0

Views: 1625

Answers (2)

Digvijay S
Digvijay S

Reputation: 2705

try this

sed -i  "s#\$#, ${contents}#g" 

Demo :

$cat file.txt 
server1.mydomain.com
$echo $contents 
1.3M /var/log/test.log
$sed -i  "s#\$#, ${contents}#g"  file.txt 
$cat file.txt 
server1.mydomain.com, 1.3M    /var/log/test.log
$

sed command usage is s#pattern to search#pattern/String replacement#occurence

Upvotes: 1

Shawn
Shawn

Reputation: 52336

This is easier done with perl or another language, to avoid the issues with characters in your variable causing sed parse errors:

contents=$(du -sh /var/log/test.log) perl -pi -e '$_ .= ", $ENV{contents}" if /test_string/' "$filename"

Or using ed to edit the file, and avoiding the $contents variable completely:

ed -s "$filename" <<'EOF'
/test_string/a
,<space>
.
r !du -sh /var/log/test.log
.-2,.j
w
EOF

Replace <space> with a literal space.

This cryptic-at-first set of commands first moves to the first line matching the regular expression test_string, then appends a line ,<space> after it, then reads the output of the du command and inserts it in a line after that, and finally joins those three lines into one and writes the modified file back to disk.

(This assumes that the du invocation will only return one line.)

Upvotes: 0

Related Questions