Wednesday, June 11, 2008

Delete a line that has a particular string

Suppose I want to delete all the lines that have rakesh in them. Sed can come handy.

sed '/.*rakesh.*/d' old_file > new_file


Simple isn't it?

Friday, February 8, 2008

Trip or chop a particular field from input

In this post you will learn now you can trim or chop-off a particular field (column) from the input text

To delete the 19th field from a 20 field text delimited by a pipe

awk '$18 = $19 FS $20 {
NF = 18
}
1' FS="|" OFS="|"


Assign the value $19 FS $20 to field 18,
so filed 18 becomes field 19 | field 20.
Then (this works with some awks like GNU Awk and New Awk)
make the record 18 fields (NF = 18, number of fields is 18).


Created and explained by radoulov

Monday, January 14, 2008

Grepping the history = save time and energy

It happens to me almost everyday that I type a long command (combination of commands) and then after executing million other commands I need the long old command back again. What I used to do is hit up and down arrow keys on my key board and keep staring on the screen so that I don't miss the long command. This process is usually very time consuming and frustrating. Today all of a sudden I thought of grepping the history command and aahaa!!!!


simply grep the history command as under:

# history | grep perl
235 perl -e "s/rakesh/root/g;" -pi $(find . -type f)
267 perl -e "s/rakesh/root/g;" -pi $(find . -type f)


then you can just type !267 to execute the command or just copy/paste it.

try it and you will save a lot of time for sure.

Thanks

--Rakesh

Nifty Batch Rename files without a loop

All of us know that files can be batch renamed using a for loop as under:
for file in *.xml; do mv $file `echo $file | sed 's/xml/html/'`; done


but Kapil Raj on Unix forum suggested a nifty way to do it without a loop

ls -1 *.xml | nawk -F ".xml" '{print "mv ", $1".xml",$1}' | ksh


Explanation:
ls -1 ---- lists the files vertically
nawk -F ".xml" '{print "mv ", $1".xml",$1}' ---- gets the input from ls -1 and treats .xml as the delimiter. So, if the file name is abc.xml.pqr then $1 would have abc and $2 would have pqr. Also awk prepares the input for a shell (ksh) in the format mv abc.xml.pqr abc.pqr

ksh ---- receives input from nawk and executes mv abc.xml.pqr abc.pqr (renames)



Note: This process is not recursive.


Recursiveness can be obtained by using unix find command.

Ideas and comments are welcome