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

Posted: June 30, 2016. At: 1:04 PM. This was 1 year ago. Post ID: 9379
Page permalink.
WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters. These cookies expire two weeks after they are set.

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() {
        printf(".");
 
        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{} {
        printf{"."};
 
        return 0;
}

Convert all lowercase text into uppercase.

jason@DESKTOP-R72SPS3:/mnt/c/Users/johnc/Documents$ tr [:lower:] [:upper:] < ip.c
#INCLUDE <STDIO.H>
 
INT MAIN() {
        PRINTF(".");
 
        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()  {
        printf(".");
 
        return  0;
}

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

Leave a Reply