Sunday, December 25, 2011

Linux Util 1

1) To paste one of the columns of a multi-column file as one other column in the same file:
cut -f3 -d' ' fname1|paste -d' ' - fname1 > fname2

This command takes the 3rd column of file fname1 and pastes it as first column and writes the content to file fname2. Rename the file fname2 to fname1 to avoid keeping duplicate copies. The hyphen in the paste command can be switched to last to make the 3rd column as the last column instead of first. Here the column separator is the space character given after the '-d' switch.


2) I forget to leave space around binary operator used in expr command in shell scripting.

3) I  keep forgetting about the rules of double quotes and single quotes usage in shell scripting. If you give a single quoted word inside double quoted sentence, the single quote is not interpreted, but a $variable is substituted with its value.

4) To find all C/C++ program files and related header files:

find . -regex '.*\.\(c\|h\|cxx\|cpp\)' -print

This command fetches files with extension .c, .h, .cxx, .cpp and prints their path from the current directory. Please note the extra characters ".*." in the front. The second dot is escaped and so is the first open parenthesis and logical OR symbol '|'.

5) A modification to the above command is by replacing the last 'print' option to 'print0'. That is append number zero to print word. This will display all the file names in one line as against the previous output that prints one file name in one line.

6) If you want the contents of all these files in one go, give the following:

find . -regex '.*\.\(c\|h\|cxx\|cpp\)' -print0|xargs -o cat

7) To remove all spaces in the filenames of a directory, get inside the directory and type in command line:

rename 's/ //g' *

Here, the single space after first '/' is important. Replace '*' with other names if you do not want to apply this change to all files.

No comments:

Post a Comment