| 1 | #!/bin/bash |
| 2 | # grp.sh: Rudimentary reimplementation of grep. |
| 3 | |
| 4 | E_BADARGS=85 |
| 5 | |
| 6 | if [ -z "$1" ] # Check for argument to script. |
| 7 | then |
| 8 | echo "Usage: `basename $0` pattern" |
| 9 | exit $E_BADARGS |
| 10 | fi |
| 11 | |
| 12 | echo |
| 13 | |
| 14 | for file in * # Traverse all files in $PWD. |
| 15 | do |
| 16 | output=$(sed -n /"$1"/p $file) # Command substitution. |
| 17 | |
| 18 | if [ ! -z "$output" ] # What happens if "$output" is not quoted? |
| 19 | then |
| 20 | echo -n "$file: " |
| 21 | echo "$output" |
| 22 | fi # sed -ne "/$1/s|^|${file}: |p" is equivalent to above. |
| 23 | |
| 24 | echo |
| 25 | done |
| 26 | |
| 27 | echo |
| 28 | |
| 29 | exit 0 |
| 30 | |
| 31 | # Exercises: |
| 32 | # --------- |
| 33 | # 1) Add newlines to output, if more than one match in any given file. |
| 34 | # 2) Add features. |