Find contents or string in current or subfolder files using grep and its option


Environment and Prerequisite

  • Linux base system
  • Bash shell(/bin/bash)


grep command

What is grep?

grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
  • grep: Print lines matching a pattern. It can be used with other commands and various options.


Find contents in all subfolder files using r and n option

Usage

  • Use below command in folder or directory where you want to find
grep -rn [PATTERN]

Basic example

  • -r: Find all subdirectory files recursively
  • -n: Print matching string with line number
$ grep -rn "abc def hij"
test/test_ascii.txt:2:abc def hij

Find many of patterns

  • -e: You can find more than one pattern => OR
$ grep -rn -e "send" -e "test"
.gitignore:41:# Unit test / coverage reports
.gitignore:47:nosetests.xml
.gitignore:51:.pytest_cache/
smc_on_in_text:13:0 10 17 * * python /home/twpower/MailReminder/reminder.py >> /home/twpower/test.txt
smc_on_in_text:14:50 10 * * 3 python /home/twpower/MailReminder/reminder.py >> /home/twpower/test.txt
...

Exclude specific pattern

  • -v: Exclude specific pattern
$ grep -rn -e "send" -e "test" | grep -v ".gitignore"
smc_on_in_text:13:0 10 17 * * python /home/twpower/MailReminder/reminder.py >> /home/twpower/test.txt
smc_on_in_text:14:50 10 * * 3 python /home/twpower/MailReminder/reminder.py >> /home/twpower/test.txt
reminder.py:6:def sendMail(sender_email, receiver_email, app_password ,msg):
reminder.py:9:    smtp.login(sender_email, app_password)
...

Give specific directory

  • You can give specific directories as arguments.
$ grep -rn -e "def sednMail" -e "with open" MailReminder ./test/neutron
MailReminder/reminder.py:19:with open('/home/twpower/MailReminder/account.json') as account_json_file:
./test/neutron/doc/source/contributor/internals/quality_of_service.rst:349:combination with openflow rules.
...


Reference

patch 파일을 만들고 적용해보자.


환경

  • Linux 기반 시스템
  • Bash shell(/bin/bash)
  • patch, diff 그리고 git 명령어


patch, diff 그리고 git 명령어

patch 명령어

patch -pNUM < patchfile
  • patch: 패치파일을 이용해 프로젝트나 파일에 패치를 적용하는 명령어입니다.
  • 패치파일은 diffgit diff를 이용해 만들 수 있습니다.


diff 명령어

diff [OPTION]... FILES
  • diff: 두 파일 또는 프로젝트의 diff를 줄별로 비교 및 분석해주는 명령어입니다.
  • 자세한 예제는 아래 나와있습니다.


git diff 명령어

git diff
  • git diff: 현재 git이 있는 프로젝트에서 어떤 파일들이 바뀌었는지를 나타내는 명령어입니다.
  • git diff를 이용해 바로 patch 파일을 만들 수 있습니다.


diff를 이용해 patch 파일 만들기

두 파일간에 patch 파일 만들기

사용법

diff -urN [old file] [patched file]

예시

# Make diff
diff -urN test-old.txt test-new.txt

# Make patch file
diff -urN test-old.txt test-new.txt > patch.patch


프로젝트 폴더간 patch 파일 만들기

사용법

diff -urN [old directory] [patched directory]

예시

# Make diff
diff -urN neutron neutron_patched

# Make diff file
diff -urN neutron neutron_patched > neutron_patch.patch


git diff로 patch 파일 만들기

  • 바로 명령어를 사용해 파일로 남겨주시면 됩니다.
git diff > [patch file name]


patch 파일을 적용하기

사용법

patch -pNUM < patchfile
  • 패치를 할 프로젝트나 파일의 위치에서 위의 명령어를 사용해 적용합니다.
  • NUM은 패치 파일에 나와있는 경로에서 몇개를 제외할지를 나타냅니다. 예를 들어서 패치파일에 a/neutron/service.py로 나와있고 -p1을 하게 되면 앞에서 하나의 경로를 제외한 neutron/service.py에 적용이 되게 되며 만약 -p2를 하게 된다면 service.py에 적용이 되게 됩니다.


예시

  • neutron 프로젝트 안에서 패치 적용
  • neutron_patch.patch 파일이 neutron 프로젝트 폴더 바로 바깥에 미리 생성되어 있어야 합니다.
# In neutron project
cd neutron

# Apply patch file
# Option -p1 could be different depends on your patch file
patch -p1 < ../neutron_patch.patch


사용 예제

0. 과정

  • neutron 프로젝트를 clone하고 파일을 조금 변경한 후에 git diff를 이용해 patch 파일을 생성합니다.
  • neutron 프로젝트를 다시 원상태로 복구하고 patch 파일을 적용해서 파일이 바뀌는지 확인합니다.

1. neutron 프로젝트 클론 및 수정

git clone https://github.com/openstack/neutron.git
cd neutron

vi [any file in this project directory]

1. 사용할 patch 파일 생성

  • patch 파일은 자유롭게 만드셔도 됩니다.
git diff > ../neutron_patch.patch

neutron_patch.patch

diff --git a/neutron/service.py b/neutron/service.py
index 06bf4cd..67f93fe 100644
--- a/neutron/service.py
+++ b/neutron/service.py
@@ -1,4 +1,4 @@
-# Copyright 2011 VMware, Inc
+#aidfjaldfja;ifdjsaoe# Copyright 2011 VMware, Inc
 # All Rights Reserved.
 #
 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
diff --git a/neutron/worker.py b/neutron/worker.py
index 81e7110..a330fe0 100644
--- a/neutron/worker.py
+++ b/neutron/worker.py
@@ -9,7 +9,7 @@
 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 #    License for the specific language governing permissions and limitations
 #    under the License.
-
+#akdfjakl;dfja;kfld
 from neutron_lib import worker
 from oslo_config import cfg
 from oslo_service import loopingcall

2. patch 파일 적용

  • neutron을 원상태로 복구하고 아래 명령어를 시행합니다.
patch -p1 < ../neutron_patch.patch


참고자료

Make patch file and apply it.


Environment and Prerequisite

  • Linux base system
  • Bash shell(/bin/bash)
  • patch, diff and git command


patch, diff and git command

patch command

patch -pNUM < patchfile
  • patch: Apply a patch file to an project or file.
  • Patch file can be made by using diff or git diff.


diff command

diff [OPTION]... FILES
  • diff: Compare files or projects line by line
  • Detail example is in below.


git diff command

git diff
  • git diff: Show current git project’s diff status.
  • You can make patch file using git diff command.


Make patch file using diff

Make patch file between two files

Usage

diff -urN [old file] [patched file]

Example

# Make diff
diff -urN test-old.txt test-new.txt

# Make patch file
diff -urN test-old.txt test-new.txt > patch.patch


Make patch file between two project directories

Usage

diff -urN [old directory] [patched directory]

Example

# Make diff
diff -urN neutron neutron_patched

# Make diff file
diff -urN neutron neutron_patched > neutron_patch.patch


Make patch file using git diff

  • Directly use git command
git diff > [patch file name]


Apply patch file

Usage

patch -pNUM < patchfile
  • In project or file directory that you want to apply patch, use above command.
  • NUM means that how many root directories you are going to remove in patch file. For example, in patch file there is file patch like a/neutron/service.py. If we use -p1 option, then patch will be applied file path neutron/service.py. If we use -p2 option, then patch will be applied to file path service.py.


Example

  • Apply patch in neutron project directory
  • neutron_patch.patch file must exist just out of neutron project
# In neutron project
cd neutron

# Apply patch file
# Option -p1 could be different depends on your patch file
patch -p1 < ../neutron_patch.patch


Usage Example

0. Process

  • Clone neutron project and edit it for making patch file. Make patch file from git diff.
  • Revert all diffs in neutron project and apply patch file. Check patch is applied.

1. Clone neutron project and modify it

git clone https://github.com/openstack/neutron.git
cd neutron

vi [any file in this project directory]

2. Make patch file

  • Make patch file freely.
git diff > ../neutron_patch.patch

neutron_patch.patch

diff --git a/neutron/service.py b/neutron/service.py
index 06bf4cd..67f93fe 100644
--- a/neutron/service.py
+++ b/neutron/service.py
@@ -1,4 +1,4 @@
-# Copyright 2011 VMware, Inc
+#aidfjaldfja;ifdjsaoe# Copyright 2011 VMware, Inc
 # All Rights Reserved.
 #
 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
diff --git a/neutron/worker.py b/neutron/worker.py
index 81e7110..a330fe0 100644
--- a/neutron/worker.py
+++ b/neutron/worker.py
@@ -9,7 +9,7 @@
 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 #    License for the specific language governing permissions and limitations
 #    under the License.
-
+#akdfjakl;dfja;kfld
 from neutron_lib import worker
 from oslo_config import cfg
 from oslo_service import loopingcall

2. Apply patch file

  • Revert all diffs and run below command to apply patch file
patch -p1 < ../neutron_patch.patch


Reference

wc 명령어를 사용해서 파일 또는 입력의 바이트, 문자, 단어 그리고 줄(라인) 수를 세는 방법을 알아보자.


환경

  • Linux 기반 시스템
  • Bash shell(/bin/bash)


wc 명령어

wc 명령어란?

wc [OPTION]... [FILE]...
wc [OPTION]... --files0-from=F
  • wc: 주어지는 파일 또는 표준 입력의 바이트, 문자, 단어 그리고 줄(라인) 수를 출력해주는 명령어입니다.
  • wc는 ‘word count’를 의미한다고 합니다.
  • ls -al과 함께 폴더와 파일의 수를 알고 싶을때 응용이 가능합니다.


옵션별 사용법

예제에 사용할 파일 작성

  • ASCII용 예제
$ cat << EOF > test_ascii.txt
123
abc def hij
lmn opq rs
EOF

$ file test_ascii.txt
test_ascii.txt: ASCII text
  • UTF-8용 예제
$ cat << EOF > test_utf.txt
한국어 배워보세요.
감사합니다. 또 봐요!
EOF

$ file test_utf.txt
test_utf.txt: UTF-8 Unicode text

-c, –bytes 옵션

  • 파일의 바이트 수를 출력합니다.
$ wc -c test_ascii.txt
27 test_ascii.txt
# You can use it with cat command
$ cat test_ascii.txt | wc -c
27

-m, –chars 옵션

  • 문자들의 수를 출력합니다.
$ wc -m test_ascii.txt
27 test_ascii.txt
# You can use it with cat command
$ cat test_ascii.txt | wc -m
27
  • ASCII에서는 문자의 수가 곧 바이트의 수지만(문자당 1바이트) 다른 문자 형식에서는 아닐수도 있습니다.
$ wc -m test_ascii.txt
27 test_ascii.txt

$ wc -c test_ascii.txt
27 test_ascii.txt
$ wc -m test_utf.txt
24 test_utf.txt

$ wc -c test_utf.txt
56 test_utf.txt

-l, –lines 옵션

  • 줄(라인 또는 개행문자)의 수를 출력합니다.
$ wc -l test_ascii.txt
3 test_ascii.txt
$ cat test_ascii.txt | wc -l
3
  • 특정 폴더에서 파일이나 폴더의 수를 알고 싶을 때 ls -al과 같이 사용가능합니다.
$ ls -al | wc -l
9

-w, –words 옵션

  • 단어의 수를 출력합니다.
$ wc -w test_ascii.txt
7 test_ascii.txt
$ wc -w test_utf.txt
5 test_utf.txt


참고자료

Let’s count number of bytes, characters, words and lines in file or input.


Environment and Prerequisite

  • Linux base system
  • Bash shell(/bin/bash)


wc command

What is wc command?

wc [OPTION]... [FILE]...
wc [OPTION]... --files0-from=F
  • wc: print newline, word, and byte counts for each file or input
  • wc stands for ‘word count’
  • You can use it with ls -al when count number of files and directories in specific path


Usage with each option

Make sample files for examples

  • ASCII sample
$ cat << EOF > test_ascii.txt
123
abc def hij
lmn opq rs
EOF

$ file test_ascii.txt
test_ascii.txt: ASCII text
  • UTF-8 sample
$ cat << EOF > test_utf.txt
한국어 배워보세요.
감사합니다. 또 봐요!
EOF

$ file test_utf.txt
test_utf.txt: UTF-8 Unicode text

-c, –bytes option

  • print the byte counts.
$ wc -c test_ascii.txt
27 test_ascii.txt
# You can use it with cat command
$ cat test_ascii.txt | wc -c
27

-m, –chars option

  • print the character counts.
$ wc -m test_ascii.txt
27 test_ascii.txt
# You can use it with cat command
$ cat test_ascii.txt | wc -m
27
  • In ASCII format, the number of bytes and characters are same but some of other formats would be not.
$ wc -m test_ascii.txt
27 test_ascii.txt

$ wc -c test_ascii.txt
27 test_ascii.txt
$ wc -m test_utf.txt
24 test_utf.txt

$ wc -c test_utf.txt
56 test_utf.txt

-l, –lines option

  • print the newline counts.
$ wc -l test_ascii.txt
3 test_ascii.txt
$ cat test_ascii.txt | wc -l
3
  • You can count number of files and directories in specific path by using it with ls -al.
$ ls -al | wc -l
9

-w, –words option

  • print the word counts.
$ wc -w test_ascii.txt
7 test_ascii.txt
$ wc -w test_utf.txt
5 test_utf.txt


Reference