Replacing Text
Replacing text swaps old letters or words for new ones. tr swaps letters, and sed swaps words.
Small letters to capital letters
tr 'a-z' 'A-Z' swaps every small letter for its capital. The names print in capitals.
$ cd ~/practice
$ cat data/names.txt | tr 'a-z' 'A-Z'Delete one letter
tr -d 'a' deletes every a. The names print without it.
$ cd ~/practice
$ cat data/names.txt | tr -d 'a'Swap one name
sed s/ana/amy/ swaps ana for amy. The other names stay the same.
$ cd ~/practice
$ sed 's/ana/amy/' data/names.txtExample
$ cd ~/practice
$ sed 's/failed/lost/' data/logs.txt
$ cat data/names.txt | tr 'a-z' 'A-Z'Key points
- Use tr to swap one set of letters for another.
- Use tr -d to delete letters.
- Use sed to swap one word for another.
- sed s/old/new/ swaps the first match on each line.
- Both tools print the changed text and leave the file alone.
In this example, sed swaps failed for lost on the two error lines. tr swaps small letters for capitals in the names. Both tools print the new text, and the files stay the same.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which tool swaps small letters for capitals?