Register
It is currently Thu Oct 23, 2014 8:25 am

How to insert a character at the beginning of a line


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Mon Nov 25, 2013 10:18 am   

Joined: Mon Nov 25, 2013 9:40 am
Posts: 1
Hi,

Could you tell me how to insert a number sign (#) at the beginning of a line in a file? And how to remove it when needed.
e.g.
In the shadow.squid file I want to add a # with a script and remove it with another one.
If the line begins with "geroh" then add #, that's the 1st.
If the line begins with "#geroh" then remove #, that's the 2nd.

It's just to regulate when the user "geroh" can connect the Internet.

Thanxs


Top
 Profile  
 PostPosted: Mon Nov 25, 2013 7:00 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 550
hi,

that's a sed matter:
Code:
sed -i.bak '/^geroh/s/^/#/;/^#\(geroh.*\)/\1/' yourFile
this can probably be improved.


Top
 Profile  
 PostPosted: Tue Nov 26, 2013 6:44 am   
User avatar

Joined: Wed Jun 08, 2011 8:27 am
Posts: 189
Location: outer Shpongolia
Assuming your file doesn't already have comments consisting of more than one # character,

With sed(1), you can do:
Code:
sed -i.bak '/^geroh/ s/^/##/; /^#*geroh/ s/^#//' shadow.squid

You can use the same logic with a text editor:
Code:
printf '%s\n' 'g/^geroh/ s/^/##/' 'g/^#*geroh/ s/^#//' w | ed -s shadow.squid


Though, if the username isn't actually fixed, use awk(1):
Code:
file=shadow.squid
user=geroh

awk '$0 ~ "^"c"?"u { $0 ~ "^"c ? sub(c, _) : $0 = c $0 } 1' c='#' u="$user" "$file" > "$file.tmp" &&
mv "$file.tmp" "$file"

...or perl(1) for more clarity (heh):
Code:
user=geroh

perl -spi.bak -e '/^$c?$u/ && { /^$c/ ? s/^$c// : s/^/$c/ }' -- -c='#' -u="$user" shadow.squid

These solutions toggle the comments when needed, which means
that when a comment is seen it's removed, otherwise one is added.

You don't need two scripts.


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

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 4 guests


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