Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unix tr find and replace

Tags:

unix

sed

awk

tr

This is the command I'm using on a standard web page I wget from a web site.

tr '<' '\n<' < index.html

however it giving me newlines, but not adding the left broket in again. e.g.

 echo "<hello><world>" | tr '<' '\n<'

returns

 (blank line which is fine)
 hello>
 world>

instead of

 (blank line or not)
 <hello>
 <world>

What's wrong?

like image 571
Kamran224 Avatar asked Dec 01 '11 23:12

Kamran224


People also ask

How do I find and replace in Unix?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do you replace characters with tr?

`tr` command can be used with -c option to replace those characters with the second character that don't match with the first character value. In the following example, the `tr` command is used to search those characters in the string 'bash' that don't match with the character 'b' and replace them with 'a'.

How do you replace a word in Unix without opening it?

Though most common use of SED command in UNIX is for substitution or for find and replace. By using SED you can edit files even without opening them, which is much quicker way to find and replace something in file, than first opening that file in VI Editor and then changing it.

What does tr D do?

It can be used with UNIX pipes to support more complex translation. tr stands for translate. -d : delete characters in the first set from the output. To convert from lower case to upper case the predefined sets in tr can be used.


1 Answers

That's because tr only does character-for-character substitution (or deletion).

Try sed instead.

echo '<hello><world>' | sed -e 's/</\n&/g'

Or awk.

echo '<hello><world>' | awk '{gsub(/</,"\n<",$0)}1'

Or perl.

echo '<hello><world>' | perl -pe 's/</\n</g'

Or ruby.

echo '<hello><world>' | ruby -pe '$_.gsub!(/</,"\n<")'

Or python.

echo '<hello><world>' \
| python -c 'for l in __import__("fileinput").input():print l.replace("<","\n<")'
like image 114
ephemient Avatar answered Sep 19 '22 11:09

ephemient