Tag Archives: shell

Change sed’s default delimiter to delete line(s)

The problem

When you want to delete a line or several in a file using sed you need to use that syntax:

root@machine:~# sed -i '/mymatch/d' test

This will match all lines containing mymatch and delete them from the file (smartly called here test).

But what if the string you want to match contains the character / in it? Let’s try:

root@machine:~# sed -i '/http://example/d' test
sed: -e expression #1, char 8: unknown command: `/'

Obviously it fails, so what about using an other character to delimit? One could try that:

root@machine:~# sed -i '|http://example|d' test
sed: -e expression #1, char 1: unknown command: `|'

It fails too, you can try with the # character, this time it won’t give you an error, but it will just do nothing.

A solution

One solution is very simple, it’s just to backslash the character you want as the new delimiter like that:

root@machine:~# sed -i '|http://example|d' test

P.S: again, it’s pretty obvious but don’t use a character as delimiter which is already in the match, else you are back to the begining of this post. Be careful when your match is a variable.

Bash locale problem with cron

The problem

One problem that can occur when you do bash scripting concerns the locale. If you run a script directly from the prompt or from a cron, you can have some differences.

I stumbled on that problem while writing a script to send an email containing accents (in french language) using a cron. When I was executing the script from the command line, I got the email with the accents well shaped, but once it was from the cron, it was all messed up. Problem is that they were not having the same environment. So here are two working solutions to do so.

First solution (preferred one)

Set the value of LANG inside your script, a better practice would be to put it inside a configuration file that you include. Example for the french UT8:

#!/bin/bash
export LANG=fr_FR.utf8

This solution is very practical, you get the same behavior wether you call it directly in command line or from the cron. Also the maintenance is easier, if you need to switch locale, you have your config file for this 🙂

Second solution

A more dirty and deprecated way is to write the file /etc/environment with the LANG variable too. How to do (french UTF8 example):

root@machine:~# echo "LANG=fr_FR.utf8" > /etc/environment

So as I said, this solution is deprecated and not really wise because the locale will be set for all crons ! Maybe it’s what you want, but the first solution allows you to have a different locale in different scripts.

 

P.S: “weird” behaviors can occur not only with the locale when you are using a cron, it’s possible that the PATH is different. Again you can define directly the PATH inside your script. For example, one thing you can do is an echo of the PATH in the command line, and then copy the value inside your script, this way, the cron will use the same PATH.