*NIX Tricks

[sed] Replace a tab character using sed

Posted in sed by kousik on May 7, 2012

Here’s how to replace all instances of TAB in a file input_file by, say comma (,), using sed

$ sed 's/<TAB>/,/g' input_file

But what is <TAB> above? On Linux systems you may just type \t (which is the regular expression for TAB) in place of <TAB>. However,  on some other systems (e.g., OSX with FreeBSD) it does not work. In cases where it doesn’t work, invoke <TAB> by hitting Control+v followed by the TAB key. This may alternatively be achieved by hitting Control+v followd by Control+i, as well.

References: ATOzTOA, Stack Overflow.

[perl] Search and replace text in multiple files from the command line

Posted in cli, linux, osx, perl, unix by kousik on January 28, 2010

$ perl -pi -w -e 's/foo/bar/g;' *.txt

-e means execute the following line of code.
-i means edit in-place
-w write warnings
-p loop

It will search for “foo” in files with extension .txt and replace it with “bar”.

Credit: here.

Tagged with: , , , ,

[regex] Reqular expressions: basics reference card

Posted in awk, grep, linux, regex, unix by kousik on January 14, 2010

[a-d] – Match one character with in a-d i.e. a, b, c, d
[^a-d] – Match one character not in the range a-d
\<test\> – Match whole word test
test\> – Match words that ends with test
\<test\> \1ing – Match following text “test testing”, \1 maps to first tag i.e \(\)
x\{5,\} – Match at least 5 occurrences of x
x\{5,9\} – Match between 5 to 9 times occurrences of x
^test – Looks for test at the beginning of a line
test$ – Looks for test at the end of the line
^test$ – Looks for test on a line by itself
th.t – “.” matches one character i.e. 4 letters has th + any character and ends with t. Example: this, that are valid matches
\. – Look for period, using “\” one can escape metacharacters

Search and replace:
:s/\(square\) and \(fair\)/\2 and \1/ – searches for “square and fair” and replaces it with fair and square

[cli] Reinovoke previous commands by changing a part of it

Posted in cli by kousik on September 26, 2009

Replace foo by bar:
$ ^foo^bar

The above changes just one instance of foo by bar; to change multiple instances use:
$ !n:gs/foo/bar/
where n is the command number (replace it with “!” for previous command).

Tagged with: ,
Follow

Get every new post delivered to your Inbox.