25 Jun

Replace one string by another in all file found by find.

find . -name *whatyouwant* -exec perl -pi.bak -e 's/TEXT_TO_REPLACE/TEXT_TO_REPLACE_IT_WITH/g' {} \;
18 Dec

This command takes an input file and substitutes strings inside it with the parameters passed, similar to substituting for variables. For example, here is an input file:

$cat temp The COLOR fox jumped over the TYPE fence. Were you to substitute the strings “COLOR” by “brown” and “TYPE” by “broken”, you could use:$ m4 -DCOLOR=brown -DTYPE=broken temp
The brown fox jumped over the broken fence.

Else, if you want to substitute “white” and “high” for the same:

\$ m4 -DCOLOR=white -DTYPE=high temp
The white fox jumped over the high fence.

25 Nov

Change all occurrences of ‘one’ to ‘two’ in the file.txt file in the grep example, enter this:

sed 's/one/two/g' file.txt
29 Jun

The command to convert all \n in a file to another string – very useful for list code generation.

perl -ne 's/\\n/\',\'/g;print;' file.txt>new.txt
12 Mar

Replaces all instance of ‘<old string>’ with ‘<new sting>’ in all the files of the current directory.

perl -pi -e "s/<old string>/<new string>/g;" *

[tags]perl,command,rename,replace,string[/tags]

07 Mar

This will join all lines of a file together. Sometimes I have a list of something in a file, one line per item and want to convert it to a comma(colon,tab)-separated line (with no trailing separator of course) that can be used as a command-line parameter to some other tool.

perl -e '@_=; chomp(@_); print join(";",@_);' < data_file