We highly recommend downloading the files for this Q&A and following along with us:

wget https://courses.cs.washington.edu/courses/cse391/24au/lectures/7/questions7.zip
unzip questions7.zip

  1. Suppose that we have the following file called emails.txt, where each line contains a list of a person’s emails:

    scot@uw.edu, scot@cs.washington.edu
    may@tech-company.com
    ning@nonprofit.ngo
    
    What is the command to print the contents of the file such that all of the @ symbols are replaced with at (there should be spaces on either side), The output should look like:
    scot at uw.edu, scot at cs.washington.edu
    may at tech-company.com
    ning at nonprofit.ngo
    

    Solutions
    sed -r 's/@/ at /g' emails.txt
    
  2. The following file, poem.txt, is a short poem which has been poorly formatted:

    I      see      you  driving
    round town    with           the  one I love
    and   I'm like   haiku
    
    Write a command that outputs poem.txt such that there is only a single space between each word.

    Solutions
    sed -r 's/ +/ /g' poem.txt
    
    # or
    sed -r 's/\s+/ /g' poem.txt
    
  3. One of the new developers at faang introduced a bug into the source code that incorrectly logged ticket id’s for product transactions. The contents of log.txt are as follows:

    4444-1111-2222-3333
    DDDD-AAAA-BBBB-CCCC
    
    The problem is that the first four characters should actually appear at the end of the line. Write a command that has the corrected ticket id’s (i.e.)
    1111-2222-3333-4444
    AAAA-BBBB-CCCC-DDDD
    

    Solutions
    sed -r 's/^(.{4})-(.*)$/\2-\1/g' log.txt
    
  4. The following file, secret.txt contains a conversation between two spies.

    Spy 1: I heard that you like secret kit kats
    Spy 2: Indeed. I saw Person X eating one the other day.
    Spy 1: Did you drop off the secret m&ms?
    Spy 2: No, I ate them.
    Spy 1: ...
    Spy 2: Keep that a secret.
    
    Our goal is to replace all lines of the conversation that contain the word secret with REDACTED. Our output should look like:
    REDACTED
    Spy 2: Indeed. I saw Person X eating one the other day.
    REDACTED
    Spy 2: No, I ate them.
    Spy 1: ...
    REDACTED
    

    Solutions
    sed -r 's/^.*secret.*$/REDACTED/' secret.txt
    
  5. Write a command that converts 7 letter palindromes into two words, such that the 4th character is replaced with a space and the last three characters are reversed. For example, if we ran

    echo "racecar" | YOUR_COMMAND
    
    The output would be
    rac rac
    
    Challenge: Can you write a similar command which has the same behavior, but prints nothing if the input string is not a 7-character palindrome?

    Solutions
    echo "racecar" | sed -r 's/^(...)....$/\1 \1/'
    
    # Challenge
    echo "racecar" | grep -E '^(.)(.)(.).\3\2\1$' | sed -r 's/^(.)(.)(.).\3\2\1/\1\2\3 \1\2\3/'