Motivation (Scenarios) Topic 4: Grep, Find & Sed. Displaying File Names. grep

Size: px
Start display at page:

Download "Motivation (Scenarios) Topic 4: Grep, Find & Sed. Displaying File Names. grep"

Transcription

1 Topic 4: Grep, Find & Sed grep: a tool for searching for strings within files find: a tool for examining a directory tree sed: a tool for "batch editing" Associated topic: regular expressions Motivation (Scenarios) I have a file called (something)220(something).java which contains the phrase "final exam" in a comment. Where is it? I need to find all the files in a directory tree with names containing "2013" and change to "2014". I need to find all the files and directories in a directory tree whose names contain "220" and change to "220A" I want to delete all files in a directory tree whose names end in "~" or start and end with "#" Style changes in large multi-file C program: change header comment and names of some functions. 1 2 grep Displaying File Names Use to search inside files for strings Default behavior: shows file names only if searching >1 file. Name comes from character sequence in old editor: g/re/p: globally search for a regular expression and print grep <pattern> <files> Searches files and prints all lines containing the pattern grep Frost * Flags: -h: never show file names -H: always show file names -l: show only the file names (not the matches) (lower-case L) Flags: -i: case-insensitive match -w: string must appear as an entire word, not part of a word -num: num lines of context around each match 3 4

2 No file arguments: grep reads standard input (useful for pipes!) history grep cd Grep as a filter Using grep in a conditional exit status: 0 = at least one match was found 1 = no matches found 2 = error useful flag: -q: no output (quiet) if grep -q $word $filename then Regular Expressions Pattern to grep in previous examples: literal value For more complex searches: use a regular expression In this course: using extended regular expression syntax much easier than the default syntax! use -E flag (or egrep command) put patterns inside single quotes Regular expressions not to be confused with wildcards in file names! Match A Single Character. in pattern: matches any single character grep -E 'n.t' * Matches: not, nat, nit, etc. Does not match: nt or naut 7 8

3 Optional Items Grouping Items?: Preceeding item is optional grep -Ew 'loved?' * Matches love or loved Can group items into one using parenthesis grep -Ew 'love(ly)?' * Matches love or lovely 9 10 Repeated Items Alternatives *: Match preceding item zero or more times +: Match preceding item one or more times {n}: Match preceding item exactly n times Examples: grep -E 'a(bc)*d' * matches ad, abcd, abcbcd, etc. grep -E 'a(bc)+d' * matches abcd, abcbcd, etc., but not ad grep -E 'a(bc){2}d' * matches abcbcd and nothing else Two regular expressions joined with matches either expression. grep -E 'red black' * Matches red or black Precedence: highest: repetition (* or +) next: concatenation (two items in a row) lowest: alternation ( ) When in doubt, use parenthesis 11 12

4 Bracket Expressions Sequence of characters in brackets: matches any one of those characters. grep -E 'n[aeiou]t' * Maches nat, net, nit, not, nut Use dash to specify a character range: [b-d] matches b, c or d [b-dr-t] matches b,c,d,r,s or t ^ at the beginning of a bracket expression: matches any character except the characters in the bracket [^b-dr-t] matches any character that is not b,c,d,r,s or t Character Classes Special notation for matching common groups of characters [:digit:] [:alpha:] - any letter (upper or lower case) & more on summary sheet These may used only inside bracket expressions Examples: egrep -w '[[:alpha:]]{4}' egrep 'linux[[:digit:]]{2}\.[[:digit:]]+' egrep -w '[[:alpha:]123]+' Matching Word & Line Positions Quoting Special Characters \<: matches beginning of word (letters, digits, underscores) \>: matches end of word ^: matches start of line $: matches end of line These are not characters! They match positions only. \ before any character that normally has a special meaning means match the character literally. matches any single character \. matches a period

5 Reminder For Grep Grep matches any line with with a substring that matches the pattern. grep 'cat' Matches any line containing cat. Not necessary to write egrep '^.*cat.*$' Backreferences Preliminary note: What does the following match? (cat dog){3} Each match of (cat dog) can be different. If that's not what you want, use backreferences. \1: the substring matched by the first parenthesized sub-expression \2, \3, etc... (Jar Nicely)-\1 matches Jar-Jar or Nicely-Nicely does not match Jar-Nicely or Nicely-Jar find (1) Searches directory trees for files having particular properties. General form: find [dir...] [test...] [action...] Default action: print name of file Simplest way to use: find files based on their names. find the file called podcast220.xml find all CSS files (names ending with.css) Searches directory and its sub-directories no limit on depth case-insensitive name match: find web220 iname '*.html' Note: find includes hidden files and directories (names starting with ".") find (2): finding files by type find web220 type f shows names of all regular files in web220 find web220 type d shows names of all directories in web220 find web220 type l shows names of all symbolic links in web220 Can combine tests: all must be true find web220 type d name 's*' shows names of all directories whose names start with s 19 20

6 find (3): finding files by size find web220 size 4157c prints name of all files whose size is exactly 4157 bytes find web220 size +4157c prints name of all files in web220 whose size is > 4157 bytes find web220 size -4157c prints name of all files in web220 whose size is < 4157 bytes find (4): finding files by age find web220 mtime 4 prints names of all files modified 4 days ago (number of days rounded down) find web220 mtime +4 prints names of all files modified more than 4 days ago -10 for less than 10 days ago size modifiers: c = bytes k = kilobytes M = megabytes G = gigabytes Sizes are rounded up! find (5): finding files by age, continued -mtime asks about time in days -mmin asks about time in minutes find web220 mmin -240 shows names of files modified less than 4 hours ago -atime and amin ask about access times, not modification times find web220 amin -240 shows names of files looked at less than 4 hours ago find (6): actions Default action: -print (print the name of the file) Another possible action: -delete Handy for cleaning up. (Careful: no confirmation!) emacs creates backup files ending in ~ find mydir name '*~' delete Deletes all emacs backup files Suppose you'd like to see the names of the files that are deleted. Use print action first. find mydir name '*~' print delete 23 24

7 find (7): Combining with other Programs Goal: use find to identify files and then run other programs on those files. FILES=$(find...) for FILE in $FILES do... commands using $FILE done Caution:file names containing spaces are a problem! Examples clean-up script Use find to write-protect a directory tree Show just the base names of all files in directory Find all files in web site containing the word "quiz" or: for FILE in $(find...) do... commands using $FILE done sed Simple Ways To Run Sed sed = a "stream editor" editing in batch mode automates repetitive edits Scenario: CISC 123 last offered in fall 2006 Offering CISC 123 again in winter 2015, need new web site To start web site: copy all files, make some global changes (fall to winter, 2006 to 2015, instructor's name, etc) Options: 1. Open each file by hand and make the edits. 2. Write a Java/C/Python program to make the edits 3. Write a script using find & sed to run program on all files Which option sounds like less work? Which option is more error-prone? To run a single sed command on one or more files: sed -r -e 'command' filename1 filename2... Output goes to standard output (can redirect or pipe) -r means use extended regular expression syntax (like -E for grep) -e means next argument will be a sed command Can combine, but e must come last: sed -re 's/mary/martha/' myfile > newfile No file name: apply command to standard input (useful for pipes or experiments) 27 28

8 Simple Substitute Command in sed Global Substitutions s/pattern/replacement/ pattern = regular expression replacement: string to substitute for the match s/mary/martha/ First occurrence of Mary in each line replaced by Martha. s/pattern/replacement/g means replace all non-overlapping instances of pattern s/pattern/replacement/2 means replace second instance of pattern Regular Expressions in Sed Which Match? (1) Substitution patterns in sed can be regular expressions. Sometimes input line matches pattern in more than one way. sed -re 's/[0-9]+/number/' Question: What will the following command do sed -re 's/[0-9]*/number/' to this input line: My cat is 16 years old. 1. Non-overlapping matches sed -re 's/one/two/' Input line: one three one sed uses the first match Output: two three one 31 32

9 Which Match? (2) Which Match? (3) Sometimes input line matches pattern in more than one way. Sometimes input line matches pattern in more than one way. 2. Two matches starting at the same spot sed -re 's/a.+b/z/' Input line: axxbxxb Two possible matches: axxbxxb or: axxbxxb sed uses the longer match output is: Z 3. Overlapping matches sed -re 's/a[a-z]{5}/z/' Input line: abcabcdefg Two possible matches: abcabcdefg or: abcabcdefg sed uses the first match output is: Zdefg Advice Using File of Commands Try to make your regular expressions as specific as possible If you want a 6-letter word starting with 't' Possible patterns: t.{5} \<t.{5}\> \<t[[:alpha:]]{5}\> For more than simple one-time edits, put commands in file. Why? only have to type them once easy to include multiple commands sed -rf scriptfile inputfile Applies all commands in scriptfile to inputfile

10 Multiple Commands Suppose script contains these two lines: s/tuesday/wednesday/ s/tues/thurs/ And testfile contains just one line: Today is Tuesday. Command: sed -rf script testfile What will the output be?? Sed's Execution Cycle For every line in the input: 1. Read the next line of input into the "pattern space" 2. Execute all commands in order. Each command operates on the pattern space, not the original line Commands may change the pattern space 3. When all commands are finished for this line, print the pattern space to the standard output. Some commands change this loop we'll see examples later Addresses Put an address or address range at the start of a command to specify which line(s) it applies to Example 1: 5s/Mary/Martha/ Makes the substitution on line 5 of the input only. Example 2: 1,10s/Mary/Martha/ Makes the substitution on lines 1-10 of the input only. Other Forms of Addresses /pattern/: command applies only to lines that match the pattern /Mary/s/little/big/g $: last line of input stream No address on a command: apply command to every line in the file. Caution: line numbers refer to entire input stream! sed -re '10s/a/b/' file1 file2 file3 Command applies to line 10 in the combined stream, not line 10 of each file

11 Deleting Lines Inserting Text d command: delete the current line In other words, skip any later commands that apply and do not copy the pattern space to the output Examples: 1,5d /^$/d /^ *$/d i\ text Text may be more than one line. Each line except the last must end with a backslash. Meaning: send the text to the output immediately (So it appears before the current line.) 1i\ #!/bin/bash 3i\ # comment 1\ # comment Another Example Appending Text sed script: 2i\ Extra line about Mary. s/mary/martha/g What is the effect? a\ text Like i, but text is added to output after the current line is finished. In terms of execution cycle: Text is queued to be output at the end of the current cycle, before the next line is read

12 Using sed to Change a File (1) Using sed to Change a File (2) Common mistake: Better way: sed -re 's/lamb/sheep/g' mary > mary sed -re 's/lamb/sheep/g' mary > temp mv -f temp mary Using sed to Change a File (3) Example (1) Another option: use the -i flag for sed: A sed script to clean up a C program: sed -i -re 's/lamb/sheep/g' mary Be very careful -- syntax of commands with "-i" are tricky! 1i// This program has been modified by Margaret's sed script.\ /^[[:blank:]]*$/d /\<[[:alpha:]]\>/i// One-letter variable name in the\ //following line. Please change it! Difficult to read! Treat sed scripts like programs and think about style

13 Example (2) # A sed script with improved style # Add a comment at the beginning of the file 1i// This program has been modified by Margaret's sed script.\ # Get rid of blank lines /^[[:blank:]]*$/d # Variable name "i" -> "loopcounter" s/\<i\>/loopcounter/g # Insert warning comment about other one-letter # variable names /\<[[:alpha:]]\>/i// One-letter variable name in the\ //following line. Please change it! Using the Preceeding Example sed -rf sedscript myprogram.c Output goes to standard output, myprogram.c unchanged sed -rf sedscript myprogram.c > new.c rm myprogram.c mv new.c myprogram.c New altered version of myprogram.c sed -i -rf sedscript myprogram.c myprogram.c is changed in place sed -irf sedscript myprogram.c confusing error messages! Old Quiz Problem #1 I have several C files in which I want to make two changes: 1. I have used the word "color" in many of the files and I want to correct its spelling to "colour". This should affect "color" used on its own and also inside a word ("colors", "discolor", etc.). 2. I want to remove all lines containing a macro definition -- that is, all lines that start with the character "#", possibly preceeded by spaces. (By "remove" I mean get rid of the line altogether, not replace it with an empty line.) Your job is to write a sed script called change.sed that will accomplish these two changes. I have a directory full of C files and I want to go to that directory and type this command: sed -i -rf change.sed *.c Old Quiz Problem #2 Write a grep (or egrep) command that will find and print any lines in words.txt which contain the same lower-case letter three times in a row. The three occurrences of the letter may appear three times in a row (as in "mooo") or be separated by one or more spaces (as in "x x x") but not by any other characters. For example, if words.txt contains the following three lines: The monster said "grrr"! He lived in an igloo only in the winter. He looked like an aardvark. your command should print just the first two lines 51 52

14 Old Quiz Problem #3 Write a script that takes a directory name as a parameter and prints a list of the base names of all of the files in that directory and its subdirectory tree, in alphabetical order. This list should not include the names of the subdirectories, just regular files. (Hint: besides find, the sort command will help here.) Old Quiz Problem #4 Suppose you have a file called poem.txt. Write a one-line command that will print every line in poem.txt that starts with a or b or c or A or B or C, and ends in a character that is not e or y or E or Y. For example, if poem.txt contains: Bananas are fruit Cherries are nice and apples are yummy cats do not eat grapes Dogs eat apples your command should print: Bananas are fruit cats do not eat grapes Old Exam Problem #1 Old Exam Problem #2 Suppose you have a file called exam.txt. Write a grep (or egrep) command that will print every line in exam.txt that contains exactly two words separated by dashes. For this command, we define a word as a sequence of upper and/or lower case letters. The line must not contain anything except dashes and the two words no spaces, numbers, other punctuation, etc. There may be dashes before the first word and/or after the last word in a line, but there may not be. For example, if exam.txt contains: ----study---study Four-words----in this ----Santa----Claus----- Happy-Hannukah -onelongword---- DONT-PANIC! ---No-more-exams-- -ALL-DONEyour command should print: ----study---study ----Santa----Claus----- Happy-Hannukah -ALL-DONE- 55 Write a shell script that will delete every file which meets all of the following conditions: The name contains the word "bad", in any capitalization as in badfile.txt, verybad.c, NOT_BAD. The file has been modified at some time in the last three days. The file is somewhere in your own directory structure i.e. in your home directory, or a subdirectory of your home directory, or a sub-subdirectory of your home directory, etc. 56

Topic 4: Grep, Find & Sed

Topic 4: Grep, Find & Sed Topic 4: Grep, Find & Sed grep: a tool for searching for strings within files find: a tool for examining a directory tree sed: a tool for "batch editing" Associated topic: regular expressions 1 Motivation

More information

ITST Searching, Extracting & Archiving Data

ITST Searching, Extracting & Archiving Data ITST 1136 - Searching, Extracting & Archiving Data Name: Step 1 Sign into a Pi UN = pi PW = raspberry Step 2 - Grep - One of the most useful and versatile commands in a Linux terminal environment is the

More information

Lecture 18 Regular Expressions

Lecture 18 Regular Expressions Lecture 18 Regular Expressions In this lecture Background Text processing languages Pattern searches with grep Formal Languages and regular expressions Finite State Machines Regular Expression Grammer

More information

Essentials for Scientific Computing: Stream editing with sed and awk

Essentials for Scientific Computing: Stream editing with sed and awk Essentials for Scientific Computing: Stream editing with sed and awk Ershaad Ahamed TUE-CMS, JNCASR May 2012 1 Stream Editing sed and awk are stream processing commands. What this means is that they are

More information

Common File System Commands

Common File System Commands Common File System Commands ls! List names of all files in current directory ls filenames! List only the named files ls -t! List in time order, most recent first ls -l! Long listing, more information.

More information

Regular Expressions 1

Regular Expressions 1 Regular Expressions 1 Basic Regular Expression Examples Extended Regular Expressions Extended Regular Expression Examples 2 phone number 3 digits, dash, 4 digits [[:digit:]][[:digit:]][[:digit:]]-[[:digit:]][[:digit:]][[:digit:]][[:digit:]]

More information

Scripting Languages Course 1. Diana Trandabăț

Scripting Languages Course 1. Diana Trandabăț Scripting Languages Course 1 Diana Trandabăț Master in Computational Linguistics - 1 st year 2017-2018 Today s lecture Introduction to scripting languages What is a script? What is a scripting language

More information

Lecture 5. Essential skills for bioinformatics: Unix/Linux

Lecture 5. Essential skills for bioinformatics: Unix/Linux Lecture 5 Essential skills for bioinformatics: Unix/Linux UNIX DATA TOOLS Text processing with awk We have illustrated two ways awk can come in handy: Filtering data using rules that can combine regular

More information

Table of contents. Our goal. Notes. Notes. Notes. Summer June 29, Our goal is to see how we can use Unix as a tool for developing programs

Table of contents. Our goal. Notes. Notes. Notes. Summer June 29, Our goal is to see how we can use Unix as a tool for developing programs Summer 2010 Department of Computer Science and Engineering York University Toronto June 29, 2010 1 / 36 Table of contents 1 2 3 4 2 / 36 Our goal Our goal is to see how we can use Unix as a tool for developing

More information

Basic Linux (Bash) Commands

Basic Linux (Bash) Commands Basic Linux (Bash) Commands Hint: Run commands in the emacs shell (emacs -nw, then M-x shell) instead of the terminal. It eases searching for and revising commands and navigating and copying-and-pasting

More information

CSE 15L Winter Midterm :) Review

CSE 15L Winter Midterm :) Review CSE 15L Winter 2015 Midterm :) Review Makefiles Makefiles - The Overview Questions you should be able to answer What is the point of a Makefile Why don t we just compile it again? Why don t we just use

More information

Regular Expressions. Todd Kelley CST8207 Todd Kelley 1

Regular Expressions. Todd Kelley CST8207 Todd Kelley 1 Regular Expressions Todd Kelley kelleyt@algonquincollege.com CST8207 Todd Kelley 1 POSIX character classes Some Regular Expression gotchas Regular Expression Resources Assignment 3 on Regular Expressions

More information

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid: 1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,

More information

Getting to grips with Unix and the Linux family

Getting to grips with Unix and the Linux family Getting to grips with Unix and the Linux family David Chiappini, Giulio Pasqualetti, Tommaso Redaelli Torino, International Conference of Physics Students August 10, 2017 According to the booklet At this

More information

UNIX files searching, and other interrogation techniques

UNIX files searching, and other interrogation techniques UNIX files searching, and other interrogation techniques Ways to examine the contents of files. How to find files when you don't know how their exact location. Ways of searching files for text patterns.

More information

Systems Programming/ C and UNIX

Systems Programming/ C and UNIX Systems Programming/ C and UNIX December 7-10, 2017 1/17 December 7-10, 2017 1 / 17 Outline 1 2 Using find 2/17 December 7-10, 2017 2 / 17 String Pattern Matching Tools Regular Expressions Simple Examples

More information

find starting-directory -name filename -user username

find starting-directory -name filename -user username Lab 7: Input and Output The goal of this lab is to gain proficiency in using I/O redirection to perform tasks on the system. You will combine commands you have learned in this course using shell redirection,

More information

Sub-Topic 1: Quoting. Topic 2: More Shell Skills. Sub-Topic 2: Shell Variables. Referring to Shell Variables: More

Sub-Topic 1: Quoting. Topic 2: More Shell Skills. Sub-Topic 2: Shell Variables. Referring to Shell Variables: More Topic 2: More Shell Skills Plan: about 3 lectures on this topic Sub-topics: 1 quoting 2 shell variables 3 sub-shells 4 simple shell scripts (no ifs or loops yet) 5 bash initialization files 6 I/O redirection

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG 1 Notice Reading Assignment Chapter 1: Introduction to Java Programming Homework 1 It is due this coming Sunday

More information

My Favorite bash Tips and Tricks

My Favorite bash Tips and Tricks 1 of 6 6/18/2006 7:44 PM My Favorite bash Tips and Tricks Prentice Bisbal Abstract Save a lot of typing with these handy bash features you won't find in an old-fashioned UNIX shell. bash, or the Bourne

More information

Regular Expressions Explained

Regular Expressions Explained Found at: http://publish.ez.no/article/articleprint/11/ Regular Expressions Explained Author: Jan Borsodi Publishing date: 30.10.2000 18:02 This article will give you an introduction to the world of regular

More information

Computer Systems and Architecture

Computer Systems and Architecture Computer Systems and Architecture Stephen Pauwels Regular Expressions Academic Year 2018-2019 Outline What is a Regular Expression? Tools Anchors, Character sets and Modifiers Advanced Regular Expressions

More information

A Brief Introduction to the Linux Shell for Data Science

A Brief Introduction to the Linux Shell for Data Science A Brief Introduction to the Linux Shell for Data Science Aris Anagnostopoulos 1 Introduction Here we will see a brief introduction of the Linux command line or shell as it is called. Linux is a Unix-like

More information

Topic 2: More Shell Skills

Topic 2: More Shell Skills Topic 2: More Shell Skills Sub-topics: 1 quoting 2 shell variables 3 sub-shells 4 simple shell scripts (no ifs or loops yet) 5 bash initialization files 6 I/O redirection & pipes 7 aliases 8 text file

More information

COMS 6100 Class Notes 3

COMS 6100 Class Notes 3 COMS 6100 Class Notes 3 Daniel Solus September 1, 2016 1 General Remarks The class was split into two main sections. We finished our introduction to Linux commands by reviewing Linux commands I and II

More information

Computer Systems and Architecture

Computer Systems and Architecture Computer Systems and Architecture Regular Expressions Bart Meyers University of Antwerp August 29, 2012 Outline What? Tools Anchors, character sets and modifiers Advanced Regular expressions Exercises

More information

Unix as a Platform Exercises + Solutions. Course Code: OS 01 UNXPLAT

Unix as a Platform Exercises + Solutions. Course Code: OS 01 UNXPLAT Unix as a Platform Exercises + Solutions Course Code: OS 01 UNXPLAT Working with Unix Most if not all of these will require some investigation in the man pages. That's the idea, to get them used to looking

More information

Basics. I think that the later is better.

Basics.  I think that the later is better. Basics Before we take up shell scripting, let s review some of the basic features and syntax of the shell, specifically the major shells in the sh lineage. Command Editing If you like vi, put your shell

More information

This lab exercise is to be submitted at the end of the lab session! passwd [That is the command to change your current password to a new one]

This lab exercise is to be submitted at the end of the lab session! passwd [That is the command to change your current password to a new one] Data and Computer Security (CMPD414) Lab II Topics: secure login, moving into HOME-directory, navigation on Unix, basic commands for vi, Message Digest This lab exercise is to be submitted at the end of

More information

Regular Expressions. Regular expressions match input within a line Regular expressions are very different than shell meta-characters.

Regular Expressions. Regular expressions match input within a line Regular expressions are very different than shell meta-characters. ULI101 Week 09 Week Overview Regular expressions basics Literal matching.wildcard Delimiters Character classes * repetition symbol Grouping Anchoring Search Search and replace in vi Regular Expressions

More information

Std: XI CHAPTER-3 LINUX

Std: XI CHAPTER-3 LINUX Commands: General format: Command Option Argument Command: ls - Lists the contents of a file. Option: Begins with minus sign (-) ls a Lists including the hidden files. Argument refers to the name of a

More information

Table Of Contents. 1. Zoo Information a. Logging in b. Transferring files 2. Unix Basics 3. Homework Commands

Table Of Contents. 1. Zoo Information a. Logging in b. Transferring files 2. Unix Basics 3. Homework Commands Table Of Contents 1. Zoo Information a. Logging in b. Transferring files 2. Unix Basics 3. Homework Commands Getting onto the Zoo Type ssh @node.zoo.cs.yale.edu, and enter your netid pass when prompted.

More information

22-Sep CSCI 2132 Software Development Lecture 8: Shells, Processes, and Job Control. Faculty of Computer Science, Dalhousie University

22-Sep CSCI 2132 Software Development Lecture 8: Shells, Processes, and Job Control. Faculty of Computer Science, Dalhousie University Lecture 8 p.1 Faculty of Computer Science, Dalhousie University CSCI 2132 Software Development Lecture 8: Shells, Processes, and Job Control 22-Sep-2017 Location: Goldberg CS 127 Time: 14:35 15:25 Instructor:

More information

Module 8 Pipes, Redirection and REGEX

Module 8 Pipes, Redirection and REGEX Module 8 Pipes, Redirection and REGEX Exam Objective 3.2 Searching and Extracting Data from Files Objective Summary Piping and redirection Partial POSIX Command Line and Redirection Command Line Pipes

More information

Shell Programming Overview

Shell Programming Overview Overview Shell programming is a way of taking several command line instructions that you would use in a Unix command prompt and incorporating them into one program. There are many versions of Unix. Some

More information

CS Advanced Unix Tools & Scripting

CS Advanced Unix Tools & Scripting & Scripting Spring 2011 Hussam Abu-Libdeh Today s slides are from David Slater February 25, 2011 Hussam Abu-Libdeh Today s slides are from David Slater & Scripting Random Bash Tip of the Day The more you

More information

Essentials for Scientific Computing: Bash Shell Scripting Day 3

Essentials for Scientific Computing: Bash Shell Scripting Day 3 Essentials for Scientific Computing: Bash Shell Scripting Day 3 Ershaad Ahamed TUE-CMS, JNCASR May 2012 1 Introduction In the previous sessions, you have been using basic commands in the shell. The bash

More information

CSE 303, Winter 2007, Midterm Examination 9 February Please do not turn the page until everyone is ready.

CSE 303, Winter 2007, Midterm Examination 9 February Please do not turn the page until everyone is ready. CSE 303, Winter 2007, Midterm Examination 9 February 2007 Please do not turn the page until everyone is ready. Rules: The exam is closed-book, closed-note, except for one 8.5x11in piece of paper (both

More information

User Commands sed ( 1 )

User Commands sed ( 1 ) NAME sed stream editor SYNOPSIS /usr/bin/sed [-n] script [file...] /usr/bin/sed [-n] [-e script]... [-f script_file]... [file...] /usr/xpg4/bin/sed [-n] script [file...] /usr/xpg4/bin/sed [-n] [-e script]...

More information

File Commands. Objectives

File Commands. Objectives File Commands Chapter 2 SYS-ED/Computer Education Techniques, Inc. 2: 1 Objectives You will learn: Purpose and function of file commands. Interrelated usage of commands. SYS-ED/Computer Education Techniques,

More information

Introduction to Linux

Introduction to Linux Introduction to Linux The command-line interface A command-line interface (CLI) is a type of interface, that is, a way to interact with a computer. Window systems, punched cards or a bunch of dials, buttons

More information

Appendix B WORKSHOP. SYS-ED/ Computer Education Techniques, Inc.

Appendix B WORKSHOP. SYS-ED/ Computer Education Techniques, Inc. Appendix B WORKSHOP SYS-ED/ Computer Education Techniques, Inc. 1 Introduction There are no workshops for this chapter. The instructor will provide demonstrations and examples. SYS-ED/COMPUTER EDUCATION

More information

POWERONE TEMPLATES A DOCUMENT DESCRIBING HOW TO CREATE TEMPLATES.

POWERONE TEMPLATES A DOCUMENT DESCRIBING HOW TO CREATE TEMPLATES. I N F I N I T Y S O F T W O R K S POWERONE TEMPLATES A DOCUMENT DESCRIBING HOW TO CREATE TEMPLATES www.infinitysw.com/help/create Templates What is a template? powerone uses templates as its primary medium

More information

CSE 374 Midterm Exam 11/2/15 Sample Solution. Question 1. (10 points) Suppose the following files and subdirectories exist in a directory:

CSE 374 Midterm Exam 11/2/15 Sample Solution. Question 1. (10 points) Suppose the following files and subdirectories exist in a directory: Question 1. (10 points) Suppose the following files and subdirectories exist in a directory:.bashrc.emacs.bash_profile proj proj/data proj/data/dict.txt proj/data/smalldict.txt proj/notes proj/notes/todo.txt

More information

Regex, Sed, Awk. Arindam Fadikar. December 12, 2017

Regex, Sed, Awk. Arindam Fadikar. December 12, 2017 Regex, Sed, Awk Arindam Fadikar December 12, 2017 Why Regex Lots of text data. twitter data (social network data) government records web scrapping many more... Regex Regular Expressions or regex or regexp

More information

Answers to AWK problems. Shell-Programming. Future: Using loops to automate tasks. Download and Install: Python (Windows only.) R

Answers to AWK problems. Shell-Programming. Future: Using loops to automate tasks. Download and Install: Python (Windows only.) R Today s Class Answers to AWK problems Shell-Programming Using loops to automate tasks Future: Download and Install: Python (Windows only.) R Awk basics From the command line: $ awk '$1>20' filename Command

More information

A Big Step. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers

A Big Step. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers A Big Step Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers Copyright 2006 2009 Stewart Weiss What a shell really does Here is the scoop on shells. A shell is a program

More information

- c list The list specifies character positions.

- c list The list specifies character positions. CUT(1) BSD General Commands Manual CUT(1)... 1 PASTE(1) BSD General Commands Manual PASTE(1)... 3 UNIQ(1) BSD General Commands Manual UNIQ(1)... 5 HEAD(1) BSD General Commands Manual HEAD(1)... 7 TAIL(1)

More information

Part III. Shell Config. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Part III. Shell Config. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26, Part III Shell Config Compact Course @ Max-Planck, February 16-26, 2015 33 Special Directories. current directory.. parent directory ~ own home directory ~user home directory of user ~- previous directory

More information

5/8/2012. Exploring Utilities Chapter 5

5/8/2012. Exploring Utilities Chapter 5 Exploring Utilities Chapter 5 Examining the contents of files. Working with the cut and paste feature. Formatting output with the column utility. Searching for lines containing a target string with grep.

More information

Scripting. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers

Scripting. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers Scripting Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers Adapted from Practical Unix and Programming Hunter College Copyright 2006 2009 Stewart Weiss What a shell

More information

Introduction to Scripting using bash

Introduction to Scripting using bash Introduction to Scripting using bash Scripting versus Programming (from COMP10120) You may be wondering what the difference is between a script and a program, or between the idea of scripting languages

More information

A shell can be used in one of two ways:

A shell can be used in one of two ways: Shell Scripting 1 A shell can be used in one of two ways: A command interpreter, used interactively A programming language, to write shell scripts (your own custom commands) 2 If we have a set of commands

More information

Linux Tutorial #4. Redirection. Output redirection ( > )

Linux Tutorial #4. Redirection. Output redirection ( > ) Linux Tutorial #4 Redirection Most processes initiated by Linux commands write to the standard output (that is, they write to the terminal screen), and many take their input from the standard input (that

More information

Introduction to Linux Basics Part II. Georgia Advanced Computing Resource Center University of Georgia Suchitra Pakala

Introduction to Linux Basics Part II. Georgia Advanced Computing Resource Center University of Georgia Suchitra Pakala Introduction to Linux Basics Part II 1 Georgia Advanced Computing Resource Center University of Georgia Suchitra Pakala pakala@uga.edu 2 Variables in Shell HOW DOES LINUX WORK? Shell Arithmetic I/O and

More information

Understanding Regular Expressions, Special Characters, and Patterns

Understanding Regular Expressions, Special Characters, and Patterns APPENDIXA Understanding Regular Expressions, Special Characters, and Patterns This appendix describes the regular expressions, special or wildcard characters, and patterns that can be used with filters

More information

CS 307: UNIX PROGRAMMING ENVIRONMENT FIND COMMAND

CS 307: UNIX PROGRAMMING ENVIRONMENT FIND COMMAND CS 307: UNIX PROGRAMMING ENVIRONMENT FIND COMMAND Prof. Michael J. Reale Fall 2014 Finding Files in a Directory Tree Suppose you want to find a file with a certain filename (or with a filename matching

More information

Linux Text Utilities 101 for S/390 Wizards SHARE Session 9220/5522

Linux Text Utilities 101 for S/390 Wizards SHARE Session 9220/5522 Linux Text Utilities 101 for S/390 Wizards SHARE Session 9220/5522 Scott D. Courtney Senior Engineer, Sine Nomine Associates March 7, 2002 http://www.sinenomine.net/ Table of Contents Concepts of the Linux

More information

CSE 374 Midterm Exam Sample Solution 2/6/12

CSE 374 Midterm Exam Sample Solution 2/6/12 Question 1. (12 points) Suppose we have the following subdirectory structure inside the current directory: docs docs/friends docs/friends/birthdays.txt docs/friends/messages.txt docs/cse374 docs/cse374/notes.txt

More information

Introduction p. 1 Who Should Read This Book? p. 1 What You Need to Know Before Reading This Book p. 2 How This Book Is Organized p.

Introduction p. 1 Who Should Read This Book? p. 1 What You Need to Know Before Reading This Book p. 2 How This Book Is Organized p. Introduction p. 1 Who Should Read This Book? p. 1 What You Need to Know Before Reading This Book p. 2 How This Book Is Organized p. 2 Conventions Used in This Book p. 2 Introduction to UNIX p. 5 An Overview

More information

CSCI 2132: Software Development. Norbert Zeh. Faculty of Computer Science Dalhousie University. Shell Scripting. Winter 2019

CSCI 2132: Software Development. Norbert Zeh. Faculty of Computer Science Dalhousie University. Shell Scripting. Winter 2019 CSCI 2132: Software Development Shell Scripting Norbert Zeh Faculty of Computer Science Dalhousie University Winter 2019 Reading Glass and Ables, Chapter 8: bash Your Shell vs Your File Manager File manager

More information

COMP2100/2500 Lecture 17: Shell Programming II

COMP2100/2500 Lecture 17: Shell Programming II [ANU] [DCS] [COMP2100/2500] [Description] [Schedule] [Lectures] [Labs] [Homework] [Assignments] [COMP2500] [Assessment] [PSP] [Java] [Reading] [Help] COMP2100/2500 Lecture 17: Shell Programming II Summary

More information

Windshield. Language Reference Manual. Columbia University COMS W4115 Programming Languages and Translators Spring Prof. Stephen A.

Windshield. Language Reference Manual. Columbia University COMS W4115 Programming Languages and Translators Spring Prof. Stephen A. Windshield Language Reference Manual Columbia University COMS W4115 Programming Languages and Translators Spring 2007 Prof. Stephen A. Edwards Team members Wei-Yun Ma wm2174 wm2174@columbia.edu Tony Wang

More information

More regular expressions, synchronizing data, comparing files

More regular expressions, synchronizing data, comparing files More regular expressions, synchronizing data, comparing files Laboratory of Genomics & Bioinformatics in Parasitology Department of Parasitology, ICB, USP Regular expressions POSIX regular expressions

More information

Advanced Linux Commands & Shell Scripting

Advanced Linux Commands & Shell Scripting Advanced Linux Commands & Shell Scripting Advanced Genomics & Bioinformatics Workshop James Oguya Nairobi, Kenya August, 2016 Man pages Most Linux commands are shipped with their reference manuals To view

More information

Shells & Shell Programming (Part B)

Shells & Shell Programming (Part B) Shells & Shell Programming (Part B) Software Tools EECS2031 Winter 2018 Manos Papagelis Thanks to Karen Reid and Alan J Rosenthal for material in these slides CONTROL STATEMENTS 2 Control Statements Conditional

More information

Mineração de Dados Aplicada

Mineração de Dados Aplicada Simple but Powerful Text-Processing Commands August, 29 th 2018 DCC ICEx UFMG Unix philosophy Unix philosophy Doug McIlroy (inventor of Unix pipes). In A Quarter-Century of Unix (1994): Write programs

More information

Practice Problems For Topic 3: Shell Scripting

Practice Problems For Topic 3: Shell Scripting Practice Problems For Topic 3: Shell Scripting Parts 1-4 of this set contain short problems to help you practice new shell skills one at a time. Parts 5 and 6 are longer problems that put many of these

More information

More Scripting Techniques Scripting Process Example Script

More Scripting Techniques Scripting Process Example Script More Scripting Techniques Scripting Process Example Script 1 arguments to scripts positional parameters input using read exit status test program, also known as [ if statements error messages 2 case statement

More information

CSI Lab 02. Tuesday, January 21st

CSI Lab 02. Tuesday, January 21st CSI Lab 02 Tuesday, January 21st Objectives: Explore some basic functionality of python Introduction Last week we talked about the fact that a computer is, among other things, a tool to perform high speed

More information

Topic 6: A Quick Intro To C

Topic 6: A Quick Intro To C Topic 6: A Quick Intro To C Assumption: All of you know Java. Much of C syntax is the same. Also: Many of you have used C or C++. Goal for this topic: you can write & run a simple C program basic functions

More information

CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash

CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash CS 25200: Systems Programming Lecture 10: Shell Scripting in Bash Dr. Jef Turkstra 2018 Dr. Jeffrey A. Turkstra 1 Lecture 10 Getting started with Bash Data types Reading and writing Control loops Decision

More information

History. Terminology. Opening a Terminal. Introduction to the Unix command line GNOME

History. Terminology. Opening a Terminal. Introduction to the Unix command line GNOME Introduction to the Unix command line History Many contemporary computer operating systems, like Microsoft Windows and Mac OS X, offer primarily (but not exclusively) graphical user interfaces. The user

More information

Topic 2: More Shell Skills. Sub-Topic 1: Quoting. Sub-Topic 2: Shell Variables. Difference Between Single & Double Quotes

Topic 2: More Shell Skills. Sub-Topic 1: Quoting. Sub-Topic 2: Shell Variables. Difference Between Single & Double Quotes Topic 2: More Shell Skills Sub-Topic 1: Quoting Sub-topics: 1 quoting 2 shell variables 3 sub-shells 4 simple shell scripts (no ifs or loops yet) 5 bash initialization files 6 I/O redirection & pipes 7

More information

Unix File System. Learning command-line navigation of the file system is essential for efficient system usage

Unix File System. Learning command-line navigation of the file system is essential for efficient system usage ULI101 Week 02 Week Overview Unix file system File types and file naming Basic file system commands: pwd,cd,ls,mkdir,rmdir,mv,cp,rm man pages Text editing Common file utilities: cat,more,less,touch,file,find

More information

Getting your department account

Getting your department account 02/11/2013 11:35 AM Getting your department account The instructions are at Creating a CS account 02/11/2013 11:36 AM Getting help Vijay Adusumalli will be in the CS majors lab in the basement of the Love

More information

Useful Unix Commands Cheat Sheet

Useful Unix Commands Cheat Sheet Useful Unix Commands Cheat Sheet The Chinese University of Hong Kong SIGSC Training (Fall 2016) FILE AND DIRECTORY pwd Return path to current directory. ls List directories and files here. ls dir List

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

UNIX, GNU/Linux and simple tools for data manipulation

UNIX, GNU/Linux and simple tools for data manipulation UNIX, GNU/Linux and simple tools for data manipulation Dr Jean-Baka DOMELEVO ENTFELLNER BecA-ILRI Hub Basic Bioinformatics Training Workshop @ILRI Addis Ababa Wednesday December 13 th 2017 Dr Jean-Baka

More information

Digital Humanities. Tutorial Regular Expressions. March 10, 2014

Digital Humanities. Tutorial Regular Expressions. March 10, 2014 Digital Humanities Tutorial Regular Expressions March 10, 2014 1 Introduction In this tutorial we will look at a powerful technique, called regular expressions, to search for specific patterns in corpora.

More information

psed [-an] script [file...] psed [-an] [-e script] [-f script-file] [file...]

psed [-an] script [file...] psed [-an] [-e script] [-f script-file] [file...] NAME SYNOPSIS DESCRIPTION OPTIONS psed - a stream editor psed [-an] script [file...] psed [-an] [-e script] [-f script-file] [file...] s2p [-an] [-e script] [-f script-file] A stream editor reads the input

More information

CS Unix Tools & Scripting

CS Unix Tools & Scripting Cornell University, Spring 2014 1 February 7, 2014 1 Slides evolved from previous versions by Hussam Abu-Libdeh and David Slater Regular Expression A new level of mastery over your data. Pattern matching

More information

CS Unix Tools. Fall 2010 Lecture 5. Hussam Abu-Libdeh based on slides by David Slater. September 17, 2010

CS Unix Tools. Fall 2010 Lecture 5. Hussam Abu-Libdeh based on slides by David Slater. September 17, 2010 Fall 2010 Lecture 5 Hussam Abu-Libdeh based on slides by David Slater September 17, 2010 Reasons to use Unix Reason #42 to use Unix: Wizardry Mastery of Unix makes you a wizard need proof? here is the

More information

CSE 374 Midterm Exam 11/2/15. Name Id #

CSE 374 Midterm Exam 11/2/15. Name Id # Name Id # There are 8 questions worth a total of 100 points. Please budget your time so you get to all of the questions. Keep your answers brief and to the point. The exam is closed book, closed notes,

More information

Linux shell programming for Raspberry Pi Users - 2

Linux shell programming for Raspberry Pi Users - 2 Linux shell programming for Raspberry Pi Users - 2 Sarwan Singh Assistant Director(S) NIELIT Chandigarh 1 SarwanSingh.com Education is the kindling of a flame, not the filling of a vessel. - Socrates SHELL

More information

Do not start the test until instructed to do so!

Do not start the test until instructed to do so! Instructions: Print your name in the space provided below. This examination is closed book and closed notes, aside from the permitted one-page formula sheet. No calculators or other electronic devices

More information

PESIT Bangalore South Campus

PESIT Bangalore South Campus INTERNAL ASSESSMENT TEST - III Date : 09-11-2015 Marks : 0 Subject & Code : USP & 15CS36 Class : III ISE A & B Name of faculty : Prof. Ajoy Kumar Note: Solutions to ALL Questions Questions 1 a. Explain

More information

Advanced training. Linux components Command shell. LiLux a.s.b.l.

Advanced training. Linux components Command shell. LiLux a.s.b.l. Advanced training Linux components Command shell LiLux a.s.b.l. alexw@linux.lu Kernel Interface between devices and hardware Monolithic kernel Micro kernel Supports dynamics loading of modules Support

More information

Unix Guide. Meher Krishna Patel. Created on : Octorber, 2017 Last updated : December, More documents are freely available at PythonDSP

Unix Guide. Meher Krishna Patel. Created on : Octorber, 2017 Last updated : December, More documents are freely available at PythonDSP Unix Guide Meher Krishna Patel Created on : Octorber, 2017 Last updated : December, 2017 More documents are freely available at PythonDSP Table of contents Table of contents i 1 Unix commands 1 1.1 Unix

More information

Introduction. File System. Note. Achtung!

Introduction. File System. Note. Achtung! 3 Unix Shell 1: Introduction Lab Objective: Explore the basics of the Unix Shell. Understand how to navigate and manipulate file directories. Introduce the Vim text editor for easy writing and editing

More information

Essential Skills for Bioinformatics: Unix/Linux

Essential Skills for Bioinformatics: Unix/Linux Essential Skills for Bioinformatics: Unix/Linux SHELL SCRIPTING Overview Bash, the shell we have used interactively in this course, is a full-fledged scripting language. Unlike Python, Bash is not a general-purpose

More information

6.033 Computer System Engineering

6.033 Computer System Engineering MIT OpenCourseWare http://ocw.mit.edu 6.033 Computer System Engineering Spring 2009 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms. M.I.T. DEPARTMENT

More information

Regular Expressions. Michael Wrzaczek Dept of Biosciences, Plant Biology Viikki Plant Science Centre (ViPS) University of Helsinki, Finland

Regular Expressions. Michael Wrzaczek Dept of Biosciences, Plant Biology Viikki Plant Science Centre (ViPS) University of Helsinki, Finland Regular Expressions Michael Wrzaczek Dept of Biosciences, Plant Biology Viikki Plant Science Centre (ViPS) University of Helsinki, Finland November 11 th, 2015 Regular expressions provide a flexible way

More information

Hands on Assignment 1

Hands on Assignment 1 Hands on Assignment 1 CSci 2021-10, Fall 2018. Released Sept 10, 2018. Due Sept 24, 2018 at 11:55 PM Introduction Your task for this assignment is to build a command-line spell-checking program. You may

More information

Bash Script. CIRC Summer School 2015 Baowei Liu

Bash Script. CIRC Summer School 2015 Baowei Liu Bash Script CIRC Summer School 2015 Baowei Liu Filename Expansion / Globbing Expanding filenames containing special characters Wild cards *?, not include... Square brackets [set]: - Special characters:!

More information

Formulas and Functions

Formulas and Functions Conventions used in this document: Keyboard keys that must be pressed will be shown as Enter or Ctrl. Controls to be activated with the mouse will be shown as Start button > Settings > System > About.

More information

Command Line Interface The basics

Command Line Interface The basics Command Line Interface The basics Marco Berghoff, SCC, KIT Steinbuch Centre for Computing (SCC) Funding: www.bwhpc-c5.de Motivation In the Beginning was the Command Line by Neal Stephenson In contrast

More information

Regular Expressions. Regular Expression Syntax in Python. Achtung!

Regular Expressions. Regular Expression Syntax in Python. Achtung! 1 Regular Expressions Lab Objective: Cleaning and formatting data are fundamental problems in data science. Regular expressions are an important tool for working with text carefully and eciently, and are

More information

More Scripting and Regular Expressions. Todd Kelley CST8207 Todd Kelley 1

More Scripting and Regular Expressions. Todd Kelley CST8207 Todd Kelley 1 More Scripting and Regular Expressions Todd Kelley kelleyt@algonquincollege.com CST8207 Todd Kelley 1 Regular Expression Summary Regular Expression Examples Shell Scripting 2 Do not confuse filename globbing

More information

Lecture 3 Tonight we dine in shell. Hands-On Unix System Administration DeCal

Lecture 3 Tonight we dine in shell. Hands-On Unix System Administration DeCal Lecture 3 Tonight we dine in shell Hands-On Unix System Administration DeCal 2012-09-17 Review $1, $2,...; $@, $*, $#, $0, $? environment variables env, export $HOME, $PATH $PS1=n\[\e[0;31m\]\u\[\e[m\]@\[\e[1;34m\]\w

More information