Atomiklan
Atomiklan

Reputation: 5464

Append to the end of a specific line

Hopefully this is a simple question for someone out there. I'm pretty sure I know what I need to use, but I can't figure out how to make it work. Here's the issue:

I have a flat file database. Lets just call it file.db

Here are some sample lines from file.db

#file.db
#
line1|example|sample|name|flag|blah
line2|example|sample|name|flag|blah
line3|example|sample|name|flag|blah

Basically the script calculates a MD5 hash of a tar file. Lets say the hash of the tar file = 1234abcd

I need to append the MD5 sum and another separator (|) to a specific line in file.db

For example:

#file.db
#
line1|example|sample|name|flag|blah
line2|example|sample|name|flag|blah|1234abcd
line3|example|sample|name|flag|blah

The line that it gets appended to will of course be controlled by a variable. I have tried using sed and awk but just cannot figure out the syntax.

UPDATE

Thank you guys, have the solution now. Here is what I ended up doing:

HASH=`md5sum tmp/$URL.tgz | awk '{ print $1 }'`
DBLINE=5
awk -v OFS="|" -v l="$DBLINE" -v h="$HASH" 'NR==l{print $0,h;next}1' databases/$WEB > /tmp/$WEB.tmp && mv /tmp/$WEB.tmp databases/$WEB

Thank you Kent, and everyone else that answered.

Upvotes: 0

Views: 259

Answers (4)

Kent
Kent

Reputation: 195269

try this awk one-liner:

line=2
awk -v OFS="|" -v l="$line" 'NR==l{print $0,"123abc";next}1'

with your example input:

kent$  echo "line1|example|sample|name|flag|blah
line2|example|sample|name|flag|blah
line3|example|sample|name|flag|blah"|awk -v OFS="|" -v l="$line" 'NR==l{print $0,"123abc";next}1'                                                                           
line1|example|sample|name|flag|blah
line2|example|sample|name|flag|blah|123abc
line3|example|sample|name|flag|blah

if you want to save the output back to your original:

awk '....' file.db > /tmp/file.db.tmp && mv file.db.tmp /path/to/your/file.db

EDIT

if you need a variable for md5 hash as well:

 line=2
 hsh="whatever"
 awk -v OFS="|" -v l="$line" -v h="$hsh" 'NR==l{print $0,h;next}1'

Upvotes: 0

Sidharth C. Nadhan
Sidharth C. Nadhan

Reputation: 2253

set LN = 5
set MS = 1234abcd
sed -i.bak $LN's/$/|'$MS'/' file.db

this should work +

Upvotes: 0

user2256686
user2256686

Reputation: 245

Take a look at this quiestion. I think, it has the answer for you. I can just add that you can use regex patterns in sed:

sed '/.*line2.*/ a |123asdfasdf' out.db

Upvotes: 0

jim mcnamara
jim mcnamara

Reputation: 16399

line=2
awk -v line="$line" 'FNR==line {printf("%s%s\n" $0, "|123abcd") ;next}
                     {print $0}' infile > newfile

Upvotes: 1

Related Questions