COP 2344 (Shell Scripting) Project #2 (Solution)
Regular Expressions

 

Due: by the start of class on the date shown on the syllabus

Description:

Answer the following questions as briefly (but completely) as possible.  (These are thought exercises.  You are not supposed to type them in, but you can later, to check your answer after you have thought about it.)

Solutions

  1. What will be matched by the following regular expressions?  (Assume POSIX locale)
    x*
    Zero or more 'x'.
    [0-9]\{3\}
    A three digit number.
    xx*
    One or more 'x'.
    [0-9]\{3,5\}
    A three to five digit number.
    x\{1,5\}
    'x', 'xx', 'xxx', 'xxxx', or 'xxxxx'.
    [0-9]\{1,3\},[0-9]\{3\}
    A 4 to 6 digit number with a comma (e.g., "1,234").
    x\{5,\}
    Five or more 'x'.
    ^\...
    A string/line that begins with a period and at least two more characters.
    x\{10\}
    'xxxxxxxxxx'.
    [A-Za-z_][A-Za-z_0-9]*
    An identifier: starts with a letter or an underscore ('_'), followed by zero or more letters, digits, or underscores.
    [0-9]
    A single digit.
    \([A-Za-z0-9]\{1,\}\)\1
    An alphanumeric string that repeats (e.g., 'abcabc').
    [0-9]*
    Zero or more digits.
    ^Begin$
    The whole string equals 'Begin'.
    [0-9][0-9][0-9]
    Three digits.
    ^\(.\).*\1$
    A line/string the begins and ends with the same character.
  2. What will be the effect of the following commands?
    who | grep 'mary'
    Show logins when the username or host contains 'mary'.
    who | grep '^mary'
    Show logins when the username begins with 'mary'.
    grep '[Uu]nix' ch?/*
    Show lines containing 'unix' or 'Unix' from files in subdirectories with 3-letter names starting with 'ch'.
    ls -l | sort -k 5nr
    Show files in reverse numeric order using the file size field (to the EOL) as the key.
    sed '/^$/d' text > text.out
    Delete blank lines from file text, saving the result in text.out.
    sed 's/\([Uu]nix\)/\1(TM)/g' text > text.out
    Add '(TM)' after each 'Unix' or 'unix'.
    date | cut -c12-16
    Show the hours and minutes (better: date +%H:%M).
    date | cut -c5-11,25- | sed 's/\([0-9]\{1,2\}\)/\1,/'
    Show the month, day, and year, and add a comma after the day. (Better: date '+%b %e, %Y')
  3. Write commands to
    Find all logged-in users with usernames of at least four characters.
    who | grep '^[^ ]\{4,\}'
    Find all users on your system who's user ids are greater than 99.
    LC_ALL=C grep '^\([^:]*:\)\{2\}[0-9]\{3,\}' /etc/passwd
    Find the number of users on your system who's user ids are greater than 99.
    LC_ALL=C grep '^\([^:]*:\)\{2\}[0-9]\{3,\}' /etc/passwd | wc -l
    List all the files in your directory in decreasing order of file size (without using the -S option to ls).
    ls -l | sort -k 5,5nr