Showing posts with label sed. Show all posts
Showing posts with label sed. Show all posts

20100119

substitute multiple line pattern in sed

Today I faced a problem with a multiline replacement. I did not want to write a sophisticated regex.
I just wanted to get a copy-pasted block of code and put it in place of the old one. Selected weapon - sed.
I've chosen the /begin/,/end/ matching syntax.

['test' input file]

111
222
333
if (aaa) {
bbbbb
}xxx
}
444
while (0) {
ccccc
}
666


['change' script]

#!/usr/bin/ksh

sed '
/if (aaa)/,/\ }$/ c\
CHANGE\
WAS\
MADE
' \
test


[session]

$ ./change
111
222
333
CHANGE
WAS
MADE
444
while (0) {
ccccc
}
666

20081108

On which partition?

Last time I wrote the script for Messaging Server backups I faced the problem with proper partition selection. It's easy to achieve with a mboxutil utility... but I only need the names of the account and a corresponding partition.

Up to today I've used the solution with sed & awk. But I hate using many tools where the swiss army knife is available.
So...

# mboxutil -l -x| sed 's/.*user\/\(.*\)\/INBOX.*partition\/\(.*\)\/\=user\/.*/\1 \2/p;d'
admin primary
marcin.wisnios@somedomain.com secondary

20080630

oneliner

I use sed delete negation to remove lines that do not match the pattern.
In the following example I want to delete the improper ssh-key entries from an authorized_keys file.
Ex.

sed -e '/^environment.*USER.*/!d' .ssh/authorized_keys

I do not allow usage of ssh session without set USER environment variable.

20070917

oneliner

Task: Remove user1, user2 and user3 ssh keys from multiple machines for both home users and root account,
for ssh protocol 1 as well as protocol 2 files.

To accomplish this task I've used sed and DSH (Dancer's Shell / Distributed Shell) on Debian GNU/Linux.

I've defined the redpool host group:

# cat /etc/dsh/group/redpool
root@red1
root@red2
[...]
root@red99
root@red100


and I've done:

dsh -g redpool "sed -i '/^.*user1\|user2\|user3.*$/d' /{root,home/*}/.ssh/authorized_keys*"


But... you could sue me: "You're guilty of using multiple commands to perform your job."
So, let's ride:

for i in {1..100}; do ssh root@red$i "sed -i '/^.*user1\|user2\|user3.*$/d' /{root,home/*}/.ssh/authorized_keys*"; done


Above option is only usable with hostnames / addresses counted sequentially.
In case of various name schemes it's easier to use the dsh command.

20070803

oneliner

Remove asterisks only from the lines beginning with a specified TAG:

sed '/^TAG.*/!p; s/\*//g; n'