Wildcards and Regular Expressions.Shw

Total Page:16

File Type:pdf, Size:1020Kb

Wildcards and Regular Expressions.Shw Wildcards and Regular Expressions Hour 9 PObjectives <Regular expressions <File name wild cards and hiding wild cards from the shell <Searching for strings and patterns: grep, fgrep, and egrep Copyright © 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Hour 9 Unix Slide 1 of 12 Regular Expressions A formal language PFormal (computer) languages are categorized by their strength (i.e., by the complexity of the grammar they accept) PRegular expressions are the simplest of these languages PRegular expressions are formed with metacharacters <Some characters just represent themselves <Metacharacters have an extended, regular expression meaning <The set of metacharacters and the associated meaning vary between regular expression languages (i.e., the regular expression language accepted by Unix commands is not always the same) Hour 9 Unix Slide 2 of 12 Wildcards File name shortcuts PWildcard characters <Simplified (subset of) regular expression <Shortcut method of specifying –a single file name – multiple file names with one expression < Implemented or expanded by the shell (Bourne, Korn, C, & others) – Wildcards work with any command (including user-written programs) that accepts multiple file names on the command line PIf these characters are interpreted by a command, they can be hidden from the shell with quotation marks < " (double quote marks) inhibit wildcard expansion < ' (single quote marks) inhibit wildcard expansion, variable substitution ($varname), and command substitution (introduced later) Hour 9 Unix Slide 3 of 12 Wildcard Metacharacters Selecting related files P* (asterisk, or “splat” in Unix) matches zero or more occurrences of any character < ls * list all non-dot files (equivalent to ls) < cp c*s bak copies all files whose name begins with ‘c’ and ends with ‘s’ to directory bak P? (question mark) matches any one character < cp *.? bak copies all files whose name ends with a “dot” (period) and a single character P[xyz] matches one character from x, y, or z < cp [ABC]* /bak copies all files whose name begins with ‘A,’ ‘B,’ or ‘C’ to the bak directory P[a-z] matches one character from the range a to z < ls [A-Z]*.c lists all files whose name begins with a capital letter and end with a .c extension Hour 9 Unix Slide 4 of 12 Wildcard Examples % ls -a . .login DOCS Mail prog.c wc.c .. .profile DOCS.bak Mandel.java sprio.z wc.java .TRASH Count.p Hypo.java pgp.Z wc.asm wc.p % ls * Count.p Hypo.java pgp.Z wc.asm wc.p DOCS Mail prog.c wc.c DOCS.bak Mandel.java sprio.z wc.java %ls *.? Count.p pgp.Z prog.c sprio.z wc.c wc.p % ls [A-Z]* Count.p DOCS DOCS.bak Hypo.java Mail Mandel.java % ls *.c prog.c wc.c % ls *.[zZ] pgp.Z sprio.z % ls wc.* wc.asm wc.c wc.java wc.p % ls w*a wc.java Hour 9 Unix Slide 5 of 12 Other Wildcards Not supported by all (especially older) shells PSupported by Bourne and Korn shells P[!xyz] <matches any single character except ‘x,’ ‘y,’ or ‘z’ % ksh $ ls [!Dw]* Count.p Mail pgp.Z sprio.z Hypo.java Mandel.java prog.c Hour 9 Unix Slide 6 of 12 The grep Command Pattern matching with a regular expression processor Pgrep [ -ivlnw ] re-pattern [file ...] < -i case insensitive < -v invert test (print lines that don’t match) < -l list files but don’t print matched lines < -n print line number and matched line < -w match whole words only PInput is line-oriented text PSearches lines for a specified regular expression pattern <Processes limited regular expressions like those described in the regexp(5) manual page POutput (by default) is all lines that contain that pattern Hour 9 Unix Slide 7 of 12 grep Examples Simple regular expressions Pgrep BUFSIZ *.c <Searches for the pattern or string “BUFSIZ” in all files ending with .c <This pattern does not contain regular expression metacharacters < *.c is interpreted by the shell, not by grep Pgrep ”Cranston Snort” /etc/passwd <Searches for the string “Cranston Snort” in /etc/passwd <The quotation marks are required to “hide” the space – without the quotation marks, grep would try to search for Cranston in two files: Snort and /etc/passwd – Single quotation marks also work Pgrep -v Wilson $HOME/.phone <Searches for “Wilson” in the .phone file in the user’s home directory <Prints lines that do not contain “Wilson” <Shell expands the HOME environment variable Hour 9 Unix Slide 8 of 12 Regular Expressions See the regexp(5) or ed(1) man pages for more regular expressions PC matches character C exactly P\C escape C (treat C as a “normal” character) P. matches any single character except new-line P^R matches reg exp R when at the beginning of line PR$ matches reg exp R when at the end of the line PR* repeat regular expression R zero or more times P[xyz] matches one of x, y, or z P[^xyz] matches any one character except x, y, or z P[a-z] matches any one character from a to z P[^a-z] matches any character except in the range a to z Hour 9 Unix Slide 9 of 12 Advanced grep Examples Filtering out non-matching lines PRegular expression pattern must be hidden from shell < grep ’^Count’ prog.c < “Count must be at the beginning of the line Pgrep ’Count$’ prog.c < “Count” must be at the end of a line Pgrep ’^Count\$’ prog.c < “Count$” must be at the beginning of the line; $ is matched exactly Pmake | grep ’[Ee]rror’ <Reads standard in and searches for “Error” or “error” Pgrep ’A.*y’ /usr/dict/words <Searches the on-line dictionary for all words starting with ‘A’ and ending with ‘y’ Hour 9 Unix Slide 10 of 12 The fgrep and egrep Commands Other regular expression processors Pfgrep [ -ivlnw ] [ -f pattern-file ] string [file ...] <Fast grep: only searches for strings (i.e., no regular expressions) <Same options as grep < -f pattern-file Take the list of patterns from pattern-file Pegrep [ -ivlnw ] [ -f file ] re-pattern [file ...] <Extended or expression grep <Same options as grep < -f file Take the list of full regular expressions from file <Accepts full regular expressions as described on the regexp(5) manual page plus the following – R+ matches one or more occurrences of the full regular expression R – R? matches 0 or 1 occurrences of the full regular expression R –R1|R2 match regular expression R1 or R2 – (R) groups regular expression R for other RE operators Hour 9 Unix Slide 11 of 12 egrep Examples Great for cross word puzzles Pegrep -i ’bomb|explosive|terrorist’ mail/* <Searches for any of the words “bomb,” “explosive,” or “terrorist” <Case is not considered <Note that there are no spaces surrounding ‘|’ Pegrep ’(oo)+k’ /usr/dict/words <Searches for words with any of “ook” “ooook” “ooooook” ... Pegrep ’school(book)?’ /usr/dict/words <Searches for words that begin with “school” or “schoolbook” Pegrep ’^[Ss].....te....r$’ /usr/dict/words <Searches for a word 13 letters long <Begins with S or s <Has “te” as the 7th and 8th letters <Ends with ‘r’ Hour 9 Unix Slide 12 of 12 .
Recommended publications
  • Linux Hardening Techniques Vasudev Baldwa Ubnetdef, Spring 2021 Agenda
    Linux Hardening Techniques Vasudev Baldwa UBNetDef, Spring 2021 Agenda 1. What is Systems Hardening? 2. Basic Principles 3. Updates & Encryption 4. Monitoring 5. Services 6. Firewalls 7. Logging What is System Hardening? ⬡ A collection of tools, techniques, and best practices to reduce vulnerability in technology applications, systems, infrastructure, firmware, and other areas ⬡ 3 major areas: OS vs Software vs Network ⬠ When have we done hardening in this class before? ⬠ This lecture is focusing mostly on OS and software level Why Harden? ⬡ Firewalls can only get us so far, what happens when at attack is inside the network? ⬠ If you have nothing protecting your systems you are in trouble ⬡ We want some kind of secondary protection A Few Cybersecurity Principles ⬡ Zero Trust Security ⬠ Instead of assuming everything behind the firewall is safe, Zero Trust verifies each request as though it originates from an unsecure network ⬡ Principle of Least Privilege ⬠ Only privileges needed to complete a task should be allowed ⬠ Users should not have domain administrator/root privileges ⬡ Principle of Least Common Mechanism ⬠ Mechanisms used to access resources should not be shared in order to avoid the transmission of data. ⬠ Shared resources should not be used to access resources The Threat Model ⬡ A process by which potential threats can be identified and prioritized. ⬠ If you have a web server that feeds input to a mysql database, then protecting against mysql injections would be prioritized in your model. 2 considerations ⬡ *nix like is a very
    [Show full text]
  • HP-UX Fundamentals
    Contact Us: (616) 875-4060 HP-UX Essentials Course Summary Length: 3 Days Prerequisite: Basic computer skills Recommendation Statement: Student should be able to use a computer monitor, keyboard, mouse. Student needs to be able to input commands and control characters from a keyboard. Course Description: For those new to HP-UX, this is the first course you will take. The course starts at the beginner level and works into intermediate and advanced HP-UX commands and utilities. The student is introduced to the HP-UX Korn shell, the command line and command syntax. Although you will be exposed to the various windowing platforms available in HP-UX, this course teaches UNIX at “the command line level” to develop a thorough understanding of the HP-UX operating environment. The student learns how to navigate the HP-UX file systems and how to work with files, directories and permissions. The student will learn how to use the HP-UX editors “ex” and “vi. “ Once the student is comfortable with basic HP-UX commands, they’ll move onto advanced power tools as well as how to customize the POSIX Korn shell. The classroom labs are run in a real-world UNIX environment, are structured to allow you to learn by doing, and are developed to simulate “real world” situations. The hands-on labs progressively build your HP-UX knowledge and command skills in a clear and concise manner. Working in a controlled UNIX classroom environment with an expert instructor, you will learn HP-UX concepts and commands. You will receive professional tips and techniques that will help you build your HP-UX confidence and skills.
    [Show full text]
  • Full Workload
    Command Line: Process Control C@ELOLJ<I GifZ\jjXe[afYZfekifc =LCCNFIBCF8; !Qn\`Ycld#g_fkfZXj\%Zfd What is happening on your Linux machine? Various shell commands All of these parameters can be com- bined – for example, pstree -apu. give you details about system processes and help you control them. C`jk`e^GifZ\jj\jn`k_gj BY HEIKE JURZIK The ps command gives you a list of the processes currently running on your sys- henever you or an application ing. All other processes share this com- tem. If you do not specify any command- launch a program, the operat- mon “ancestor” – init starts the operat- line parameters, the tool will restrict the Ning system starts one or multi- ing system’s basic programs. pstree list to the current shell. If you are inter- ple processes. These processes can enter shows the relationship between “parent” ested in all of your processes, call ps various states: They can be processed, and “child” processes. This tree struc- with the x option (Listing 1). stopped, restarted, and – under normal ture shows you at a glance who is de- The tabular output in the shell tells circumstances – stopped again. Linux scended from whom (Figure 1). you the following characteristics: has something similar to access controls ฀ PID: The process identifier, a unique for processes: Only the user that started 8[[`k`feXcFlkglk number that you can use to reference a process can stop, restart, or terminate The tool gives you more detailed output a process individually. the process. if you set the -a flag. This tells pstree to ฀ TTY: The terminal or console on The only exception to this rule is the show you, in addition, the parameters which the process was started.
    [Show full text]
  • LFS-BOOK.Pdf
    Linux From Scratch Версия 7.3 Автор Gerard Beekmans Редакторы Matthew Burgess и Bruce Dubbs Перевод Иван Лабутин Linux From Scratch: Версия 7.3 by Автор Gerard Beekmans, Редакторы Matthew Burgess и Bruce Dubbs, Перевод Иван Лабутин Copyright © 1999-2013 Gerard Beekmans Copyright © 1999-2013, Gerard Beekmans Все права защищены. Эта книга выпущена под лицензией Creative Commons License. Команды для компьютера могут быть извлечены из книги под лицензией MIT License. Linux® зарегистрированная торговая марка Linus Torvalds. Linux From Scratch - Версия 7.3 Содержание Пролог ......................................................................................................................... viii i. Предисловие ........................................................................................................ viii ii. Кому адресована эта книга? ............................................................................... ix iii. Целевые архитектуры LFS .................................................................................. x iv. LFS и стандарты .................................................................................................. x v. Пояснения к выбранным пакетам ..................................................................... xii vi. Необходимые знания ....................................................................................... xvii vii. Требования к хост-системе ........................................................................... xviii viii. Соглашения, используемые в книге .............................................................
    [Show full text]
  • Linux Shell Scripting Cookbook Second Edition
    Linux Shell Scripting Cookbook Second Edition Over 110 practical recipes to solve real-world shell problems, guaranteed to make you wonder how you ever lived without them Shantanu Tushar Sarath Lakshman BIRMINGHAM - MUMBAI Linux Shell Scripting Cookbook Second Edition Copyright © 2013 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: January 2011 Second edition: May 2013 Production Reference: 1140513 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78216-274-2 www.packtpub.com Cover Image by Parag Kadam ([email protected]) Credits Authors Project Coordinator Shantanu Tushar Shiksha Chaturvedi Sarath Lakshman Proofreader Reviewers Linda Morris Rajeshwari K. John C. Kennedy Indexer Hemangini Bari Anil Kumar Sudhendu Kumar Production Coordinator Aravind SV Shantanu Zagade Acquisition Editor Cover Work Kartikey Pandey Shantanu Zagade Lead Technical Editor Ankita Shashi Technical Editors Jalasha D'costa Amit Ramadas Lubna Shaikh About the Authors Shantanu Tushar is an advanced GNU/Linux user since his college days.
    [Show full text]
  • Bash Guide for Beginners
    Bash Guide for Beginners Machtelt Garrels Xalasys.com <tille wants no spam _at_ xalasys dot com> Version 1.8 Last updated 20060315 Edition Bash Guide for Beginners Table of Contents Introduction.........................................................................................................................................................1 1. Why this guide?...................................................................................................................................1 2. Who should read this book?.................................................................................................................1 3. New versions, translations and availability.........................................................................................2 4. Revision History..................................................................................................................................2 5. Contributions.......................................................................................................................................3 6. Feedback..............................................................................................................................................3 7. Copyright information.........................................................................................................................3 8. What do you need?...............................................................................................................................4 9. Conventions used in this
    [Show full text]
  • 50 Most Frequently Used UNIX / Linux Commands (With Examples)
    17/10/13 50 Most Frequently Used UNIX / Linux Commands (With Examples) Home Free eBook Start Here Archives Contact About 50 Most Frequently Used UNIX / Linux Commands (With Examples) by Ramesh Natarajan on November 8, 2010 290 Curtir 375 Tw eet 325 This article provides practical examples for 50 most frequently used commands in Linux / UNIX. This is not a comprehensive list by any means, but this should give you a jumpstart on some of the common Linux commands. Bookmark this article for your future reference. Did I miss any frequently used Linux commands? Leave a comment and let me know. 1. tar command examples Create a new tar archive. $ tar cvf archive_name.tar dirname/ Extract from an existing tar archive. $ tar xvf archive_name.tar View an existing tar archive. www.thegeekstuff.com/2010/11/50-linux-commands/ 1/32 17/10/13 50 Most Frequently Used UNIX / Linux Commands (With Examples) $ tar tvf archive_name.tar More tar examples: The Ultimate Tar Command Tutorial with 10 Practical Examples 2. grep command examples Search for a given string in a file (case in-sensitive search). $ grep -i "the" demo_file Print the matched line, along with the 3 lines after it. $ grep -A 3 -i "example" demo_text Search for a given string in all files recursively $ grep -r "ramesh" * More grep examples: Get a Grip on the Grep! – 15 Practical Grep Command Examples 3. find command examples Find files using file-name ( case in-sensitve find) # find -iname "MyCProgram.c" Execute commands on files found by the find command $ find -iname "MyCProgram.c" -exec md5sum {} \; Find all empty files in home directory # find ~ -empty More find examples: Mommy, I found it! — 15 Practical Linux Find Command Examples 4.
    [Show full text]
  • Linux Shell Scripting Tutorial V2.0
    Linux Shell Scripting Tutorial v2.0 Written by Vivek Gite <[email protected]> and Edited By Various Contributors PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information. PDF generated at: Mon, 31 May 2010 07:27:26 CET Contents Articles Linux Shell Scripting Tutorial - A Beginner's handbook:About 1 Chapter 1: Quick Introduction to Linux 4 What Is Linux 4 Who created Linux 5 Where can I download Linux 6 How do I Install Linux 6 Linux usage in everyday life 7 What is Linux Kernel 7 What is Linux Shell 8 Unix philosophy 11 But how do you use the shell 12 What is a Shell Script or shell scripting 13 Why shell scripting 14 Chapter 1 Challenges 16 Chapter 2: Getting Started With Shell Programming 17 The bash shell 17 Shell commands 19 The role of shells in the Linux environment 21 Other standard shells 23 Hello, World! Tutorial 25 Shebang 27 Shell Comments 29 Setting up permissions on a script 30 Execute a script 31 Debug a script 32 Chapter 2 Challenges 33 Chapter 3:The Shell Variables and Environment 34 Variables in shell 34 Assign values to shell variables 38 Default shell variables value 40 Rules for Naming variable name 41 Display the value of shell variables 42 Quoting 46 The export statement 49 Unset shell and environment variables 50 Getting User Input Via Keyboard 50 Perform arithmetic operations 54 Create an integer variable 56 Create the constants variable 57 Bash variable existence check 58 Customize the bash shell environments 59 Recalling command history 63 Path name expansion 65 Create and use aliases 67 The tilde expansion 69 Startup scripts 70 Using aliases 72 Changing bash prompt 73 Setting shell options 77 Setting system wide shell options 82 Chapter 3 Challenges 83 Chapter 4: Conditionals Execution (Decision Making) 84 Bash structured language constructs 84 Test command 86 If structures to execute code based on a condition 87 If.
    [Show full text]
  • Killing Processes This Tip Shows You Some Interesting Ways to Kill Stubborn Processes
    http://www.linuxhowtos.org/Tips and Tricks/kill_processes.pdf Killing Processes This tip shows you some interesting ways to kill stubborn processes. Never let it be said that you can't kill a process again! The first way is the old boring way that most people probably use. Use the command ps aux, look through the process list until you find the PID you want and issue the kill command. How tedious! Alternatively, try using the killall command which will automatically kill a program based on its name. Code Listing 1 # killall mozilla-bin But what if you only know part of the name? Well, you could combine ps with grep, kill and awk to produce something like this. Code Listing 2 # ps aux | grep mozilla | awk '{print $2}' | xargs kill But, there's a far simpler way. Enter pkill and the closely related pgrep. These commands are part of the sys-apps/procps package and are designed to search for (or kill) running processes. So the previous command could be replaced with the following: Code Listing 3 # pkill mozilla Note: To list the PIDs instead of killing them, use pgrep. Finally, what if you have a runaway process hogging /dev/dsp, or some other file/socket? You can use fuser, which displays the PIDs of process using a specified file or filesystem. Or give it the -k option, like this, and you can easily kill those processes: Code Listing 4 # fuser -k /dev/dsp From http://www.gentoo.org/news/en/gwn/20030707-newsletter.xml image:rdf newsfeed / //static.linuxhowtos.org/data/rdf.png (null) | image:rss newsfeed / //static.linuxhowtos.org/data/rss.png
    [Show full text]
  • Intermediate Linux
    Intermediate Linux th st !!***May subroutine 30 mpi_utils_step_parallel_edge– 31 , 2016 implicit none integer ele, ierr do ele = 1, nfaces Lecturerscall mpi_isend(commvec(ele)%field1(commvec(ele)%out_i1, (in alphabetical order): & & commvec(ele)%out_j1, & Jaakko& Leinonen commvec(ele)%out_k1), & Tomasz& 1, commvec(ele)%mpi_type_out1,Malkiewicz & & commvec(ele)%to_id, commvec(ele)%to_id, & Thomas& MPI_COMM_WORLD, Zwinger send_reqs(ele), ierr) if(ierr /= MPI_SUCCESS) then call pio_abort(ierr) end if call mpi_isend(commvec(ele)%field2(commvec(ele)%out_i2, & & commvec(ele)%out_j2, & & commvec(ele)%out_k2), & & 1, commvec(ele)%mpi_type_out2, & & commvec(ele)%to_id, commvec(ele)%to_id+tag_offset, & & MPI_COMM_WORLD, send_reqs(nfaces+ele), ierr) if(ierr /= MPI_SUCCESS) then call pio_abort(ierr) end if end do #ifdef NONBLOCK do ele = 1, nfaces All material (C) 2016 by the authors. call mpi_irecv(commvec(ele)%field1(commvec(ele)%in_i1, & This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported & commvec(ele)%in_j1, & 1 License, http://creativecommons.org/licenses/by-nc-sa/3.0/ 2 & commvec(ele)%in_k1), & & 1, commvec(ele)%mpi_type_in1, & Program, May 30th 09:30 – 10:00 Morning coffee & registration 10:00 – 10:15 Introduction to the course (whereabouts, etc.) 10:15 – 10:45 Recapping Introduction to Linux (to refresh memory) 10:45 – 11:30 Basic concepts of shells 11:30 – 12:30 Lunch 12:30 – 14:30 Working with the Bash shell 14:30 – 15:00 Coffee 15:00 – 15:45 Bash job management and signals About This Course 15:45 – 16:30 Hands-on exercises & Troubleshooter: Interactive session to deal with open questions and specific problems 3 4 Program, May 31st How We Teach 09:00 – 10:00 Pipes, named pipes and redirecting All topics are presented with interactive demonstrations.
    [Show full text]
  • Introduction to Linux
    Introduction to Linux A Hands on Guide Machtelt Garrels CoreSequence.com <[email protected]> Version 1.8 Last updated 20030916 Edition Introduction to Linux Table of Contents Introduction.........................................................................................................................................................1 1. Why this guide?...................................................................................................................................1 2. Who should read this book?.................................................................................................................1 3. New versions of this guide...................................................................................................................1 4. Revision History..................................................................................................................................1 5. Contributions.......................................................................................................................................2 6. Feedback..............................................................................................................................................2 7. Copyright information.........................................................................................................................3 8. What do you need?...............................................................................................................................3 9. Conventions used
    [Show full text]
  • Section 1: Tools
    Section 1: Tools CS162 January 25, 2019 Contents 1 Make 2 1.1 More details about Make....................................2 2 Git 3 2.1 Commands to know.......................................3 3 GDB: The GNU Debugger4 3.1 Commands to know.......................................4 4 Debugging programs on Linux5 4.1 strace and ltrace.........................................5 4.2 catchsegv.............................................5 4.3 top.................................................6 4.4 ps.................................................6 4.5 pidof and pgrep..........................................6 4.6 proc................................................6 4.7 lsof.................................................7 4.8 netstat and ip...........................................7 4.9 kill, pkill, and killall.......................................7 1 CS 162 Spring 2019 Section 1: Tools Tools are important for every programmer. If you spend time learning to use your tools, you will save even more time when you are writing and debugging code. This section will introduce the most important tools for this course. 1 Make GNU Make is program that is commonly used to build other programs. When you run make, GNU Make looks in your current directory for a file named Makefile and executes the commands inside, according to the makefile language. my_first_makefile_rule: echo "Hello world" The building block of GNU Make is a rule. We just created a rule, whose target is my_first_makefile_rule and recipe is echo "Hello world". When we run make my_first_makefile_rule, GNU Make will execute the steps in the recipe and print \Hello world". Rules can also contain a list of dependencies, which are other targets that must be executed before the rule. In this example, the task_two rule has a single dependency: task_one. If we run \make task_two", then GNU Make will run task_one and then task_two.
    [Show full text]