Regular Expressions

Assignment 2 Answers

  1. Use cut to display only the file size and file name from the output of the command 'ls -l /etc'.
    $ ls -l /etc | cut -c25-32,46-
    
  2. Use cut to display only the home directories of users from the file /etc/passwd and save it in a file called 'home.txt'. Do the same with the field that contains the name of the default shell (eg. /bin/bash) and save it to a file called 'shell.txt'.
    $ cut -d: -f6 /etc/passwd > home.txt
    $ cut -d: -f7 /etc/passwd > shell.txt
    
  3. From the files above use 'paste' to create a file that contains lines with a shell and the corresponding home directory into a file called 'pasted.txt'.
    $ paste shell.txt home.txt >pasted.txt
    
  4. Translate all z to a, r to T, and m to 2.
    $ cat callofthewild.txt | tr 'zrm' aT2
    
  5. Convert the entire 'callofthewild.txt' document to uppercase.
    $ cat callofthewild.txt | tr a-z A-Z
    
  6. Create a cryptogram from a paragraph of text stored in a file called 'text.txt' and save it in a file called 'crypt.txt'. A cryptogram has one letter substituted for another to produce an unreadable code. They are usually in all uppercase with spacing and punctuation left intact.
    $ cat text.txt | tr a-z A-Z | \
    > tr A-Z AZXSWQERFDCVBNHGTYUIKJMLOP > crypt.txt
    
  7. Use sed to change the string 'Judge' to 'Mr.' in 'callofthewild.txt'.
    $ sed 's/Judge/Mr./' callofthewild.txt
    
  8. Using sed, add ', the bad dog, ' after each occurrence of 'Spitz' in lines 123 to 567 in 'callofthewild.txt'.
    $ sed '123,567s/Spitz/Spitz, the bad dog,/' \
    > callofthewild.txt
    
  9. Using sed, on lines that contain both 'Buck' and 'Spitz', add ', our hero, ' after 'Buck' in 'callofthewild.txt'.
    $ sed '/Buck.*Spitz/s/Buck/Buck, our hero,/' \
    > callofthewild.txt
    
  10. With sed you can use more than one editing instruction if you use the -e option before each one. Use only sed to change 'read' to 'eat' on lines that contain 'Buck' and 'newspapers', then display only the lines that contain 'North'.
    $ sed -n -e '/Buck.*newspapers/s/read/eat/' \
    > -e /North/p callofthewild.txt | grep read