Posted: . At: 1:04 PM. This was 8 years 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.

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() {
        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.

jason@DESKTOP-R72SPS3:/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.

jason@DESKTOP-R72SPS3:/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;
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.