Register
It is currently Mon Dec 22, 2014 1:22 am

Using variables in sed


All times are UTC - 6 hours


Post new topic Reply to topic  [ 5 posts ] 
Author Message
 PostPosted: Mon May 03, 2010 11:41 pm   

Joined: Fri Apr 30, 2010 6:42 pm
Posts: 4
Greetings,

I am having a hard time with this one. I am trying to use a for loop to update a specific line in a handful of session files. The line in the session files I am looking to append is:
Code:
HostName=

The 'hostlist' file has a list of hosts. Each line in the 'hostlist' file is unique and matches exactly to the output of 'ls'.

Here's what I have thus far:
Code:
HOST=$(cat hostlist)
for i in $(ls); do sed 's/HostName\=/HostName\=$HOST/g' $i > $i.temp; done

It doesn't matter whether I use no quotes, single quotes or double quotes, it either will add the literal $HOST to the files or nothing at all.

Since the line I am wishing to replace is the same in every file, I have also tried line replacement in sed with similar results:
Code:
#!/bin/bash

HOST=$(cat hostlist)
FILE=$(ls)

sed '2 r $HOST' $FILE > $FILE.temp


Any thoughts?

Thank you in advance!

Brenden


Top
 Profile  
 PostPosted: Tue May 04, 2010 2:16 am   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 579
Code:
export HOST="$(<hostlist)"
find . -type f -exec bash -c 'sed "s/HostName=/HostName=$HOST/g" $1 > $1.tmp' _ {} \;


Top
 Profile  
 PostPosted: Tue May 04, 2010 1:57 pm   

Joined: Fri Apr 30, 2010 6:42 pm
Posts: 4
Watael wrote:
Code:
export HOST="$(<hostlist)"
find . -type f -exec bash -c 'sed "s/HostName=/HostName=$HOST/g" $1 > $1.tmp' _ {} \;


Thank you, here is what happens:
Code:
export HOST="$(<hostlist)"
find . -type f -exec bash -c 'sed "s/HostName=/HostName=$HOST/g" $1 > $1.tmp' _ {} \;
sed: -e expression #1, char 34: unterminated `s' command
sed: -e expression #1, char 34: unterminated `s' command
sed: -e expression #1, char 34: unterminated `s' command
...ad nauseum


Brenden


Top
 Profile  
 PostPosted: Tue May 04, 2010 3:30 pm   
User avatar

Joined: Tue Apr 27, 2010 2:28 pm
Posts: 172
Location: Czech Republic
Code:
HOST=($(< hostlist))
for i in $(ls); do sed 's%HostName=%HostName='"${HOST[*]}"'%g' $i > $i.temp; done

I use % as the separator in case any of the hostnames contains /.


Top
 Profile  
 PostPosted: Wed May 05, 2010 1:41 am   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 579
c'mon please, don't ever parse ls command!
in a for loop, never ever!
fortunately, bash has glob


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 5 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP