Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Jul 132010
 

How to create a patch

Answer:

Let say you have two folders, foo and bar.

The folder bar is originally copied from the folder foo, but later you have chanegd some files inside bar.

Now you want to create a patch (We will see later, when this patch applied to foo, it will produce the same contents as in bar).

# diff -crB foo bar > bar.patch

Jun 242010
 

xargs when the filename contains a newline

Answer:

It is always handy to combine the power of find and xargs for a lot of tasks, such as

# find /tmp -type f | xargs rm -rf

However, the command will failed if the a file contains a newline character. To solve this, you can do like below.

# find /tmp -type f -print0 | xargs -0 rm -rf

Now the file list returned by the find command is terminated by a null character, so it will not mixed with the newline character if they are part of the filename. Also, the xargs -0 option will treat the null character as the delimiter (rather than newline).

Jun 222010
 

Capturing group difference in Basic Regular Expressions (BRE) and Extended Regular Expressions (ERE)

Answer:

One of the very confusion issue related to most GNU/Linux utils which are using regular expression library is they are mostly supporting the Basic Regular Expressions (BRE) by default.

E.g.

# echo "(foo)" | sed 's/\(foo\)/bar/gi'

You might expect the result is

bar

But the actual result is...

(bar)

Why the brackets are not replaced? It is because in BRE (which is the default, you don't need to escape, if you escape it, then it will be treated as a capturing group - which is quite non-sense if you came from programming background).

To solve the problem, you can just simply remove the \ escape, or you tell those commands to use ERE, e.g.

# echo "(foo)" | sed -r 's/\(foo\)/bar/gi'
bar
Jun 212010
 

Replace infile using sed and make a backup automatically

Answer:

If you use the -i flag in sed, it will replace infile, which is quite dangerous if you don't have a backup.

E.g.

# sed -i 's/foo/bar/gi' input.txt

To auto make a backup when replacing in a file, you can use

# sed -i.bak 's/foo/bar/gi' input.txt

Now the original file will stored as input.txt.bak in the same directory that you are working.