Useful shell tips. How to search and replace characters or words with the bash shell.

Search and replace on the bash shell is very useful for various one-liner shell commands. The below example shows how to replace a # character with a * character.

jason@DESKTOP-R72SPS3:/mnt/c/Users/johnc/Documents$ cat ip.c | sed 's/#/*/gi;'
*include <stdio.h>
int main() {
        return 0;

This example shows translating paranthesis into braces.

jason@DESKTOP-R72SPS3:/mnt/c/Users/johnc/Documents$ tr '()' '{}' < ip.c
#include <stdio.h>
int main{} {
        return 0;

Convert all lowercase text into uppercase.

jason@DESKTOP-R72SPS3:/mnt/c/Users/johnc/Documents$ tr [:lower:] [:upper:] < ip.c
        RETURN 0;

Write the changes to a file.

[email protected]:/mnt/c/Users/johnc/Documents$ tr [:lower:] [:upper:] < ip.c > ipupper.c

This example will cat a file and filter out any non-printable characters.

[email protected]:/mnt/c/Users/johnc/Documents$ tr -cd [:print:] < ssmaze.scr

Find a certain line in a file and then remove a character from it.

jason@DESKTOP-R72SPS3:/mnt/c/Users/johnc/Documents$ grep -i '#include' ip.c | cut -f2- -d'#'
include <stdio.h>

How to find a certain line in a file with grep and then change one character. This is how to do this with sed.

jason@DESKTOP-R72SPS3:/mnt/c/Users/johnc/Documents$ grep -i '#include' ip.c | sed 's/#/$/gi;'
$include <stdio.h>

Translate all spaces into TAB characters.

jason@DESKTOP-R72SPS3:/mnt/c/Users/johnc/Documents$ tr -s ' ' '\t' < ip.c
#include        <stdio.h>
int     main()  {
        return  0;

No comments have been made. Use this form to start the conversation :)

Leave a Reply