by 버려진Eye 2015. 9. 2. 11:33

나는 언제쯤 나의 길을 찾을까? 방황하고 계시다면, 

나는 언제쯤 자존감을 높이고 내 삶의 주인으로서 당당하게 살까?

고민하고 계시다면 서울상담심리연구소를 떠올려주세요. 

'자기이해성장 워크숍 (자존감-주도성회복)을 통해 변화를 만들수 있습니다.


서울상담심리연구소 ( http://scpi.kr , 02-3486-0826 )

 

 

 

 

[제 79차 상담대학원 입시강의(입문)-토요반 ]

 

상담대학원입시강의 (입문)은 상담심리의 길을 처음 접하시는 분들에게 효과적으로 대학원입시 준비를 하실수 있도록

돕기위하여 마련된 강의수업과정입니다. 상담사의 길을 시작하기 위해서는 상담심리대학원의 진학이 필수적이며,

대부분의 상담전공 대학원에서는 '상담심리학'과 '심리학개론'을 필수 시험과목을 선정하고 있습니다.

본 강의는 상담대학원 진학에 있어서 필수 과목인 상담심리학과 심리학개론 두 과목의 명료하게 정리하여 설명해드립니다.

상담심리전문가로 활동하시는 선생님께서 상담심리학 강의를 맡아주시고, 대학에서 심리학 강의를 하시는 교수님께서

심리학을 맡아주시기에, 시험준비에 만전을 기할 수 있습니다. 더불어 상담분야가 어떤 길인지 알수 있는 좋은 기회가

될 것입니다.

( 본 과정은 [상담대학원입시준비방법 로드맵]의 첫번째 과정으로서, 비전공이시고 혼자 공부하기 막막하신 분들께서는

이번 과정을 참여하셔서, 상담사의 길을 시작할 수 있는 초석을 다지시기 바랍니다. )

 

 

---------------------------------------------------------------------------------------------------------

 

1) 대상 : 강의에 관심있는 분들 누구나 참여가능

2) 기간 : 2014년 8월 30일 ~ 10월 4일 (6주, 16시간~20) 

            *상담심리학 : 2014년 8월30일~10월4일 토요일 오후 13:00-15:40 (박미선 교수님)

            *심리학 : 2014년 8월30일~10월4일 토요일 오후 16:00~19:20 (박준화 교수님) 

3) 장소 : 서울상담심리연구소 6A룸 (6층) (http://scpi.kr 약도 참조 -- 3호선 약수역 부근)

4) 비용 : 38만원

              비용납부 계좌 : 국민 667101-04-004211 (예금주:이채은(서울상담심리))

5) 교재 :  무료(강의 당일날 연구소 강의안으로 나가게 됩니다)

6) 신청방법 : 담당자에게 '꼭' 메일로 신청 ( 아래 '신청양식'을 사용하여 신청해주시기 바랍니다)

                   ==> 신청담당자 : seoulscpi@hanmail.net (문의 02-3486-0826)

                   ==> 필수기재사항

                   1) 강좌명 2)이름 3)연락처 4)메일주소

 

---------------------------------------------------------------------------------------------------------

** 강의/모임 환불규정 **

( 환불에 대해서는 최대한 고객을 배려하려고 합니다.  모임시작 하루 전까지 환불요청 시 불이익이 없습니다.

  모임신청 7일내 비용납부를 부탁드리며, 일정이 어려울 경우 편하게 환불받으세요.)

 

  - 강의/모임 시작 하루 전까지 환불 요청시 100% 환불
  - 강의/모임 시작 당일 환불 요청시 환불 불가함  
(단, 다음 차수의 강의로 연기가능 )    

---------------------------------------------------------------------------------------------------------

 

***주차별 교육내용

 

주차

시간

과목

강의내용

강사

1

13:00~14:20

상담과 상담이론 1

상담이란 무엇인가?

박미선

14:30~15:40

정신분석적 상담이론 1,2

16:00~17:00

 

심리학연구법

및 생리심리 개관

 

강의개요 및 심리학의 정의

박준화

17:10~18:10

심리학연구법

18:20~19:20

생리심리학 개관

2

13:00~14:20

상담이론2

인간중심적 상담이론 1,2

박미선

14:30~15:40

실존치료

16:00~17:00

 

생리심리학 &

학습심리학

 

뉴런과 정보전달

박준화

17:10~18:10

신경전달물질과 중추신경계

18:20~19:20

고전적조건형성

3

13:00~14:20

상담이론 3

행동주의 상담

박미선

14:30~15:40

인지행동적 상담이론,교류분석

16:00~17:00

 

학습심리학 &

발달심리학

 

조작적 조건형성

박준화

17:10~18:10

인지학습 발달심리 개관

18:20~19:20

인지발달

4

13:00~14:20

상담이론 4

게슈탈트 치료(형태치료)1,2

박미선

14:30~15:40

현실요법적 접근

16:00~17:00

 

발달심리학

성격심리학

 

사회성 발달 도덕발달

박준화

17:10~18:10

동기와 정서 성격심리 개관

18:20~19:20

정신분석

5

13:00~14:20

상담의과정

상담의 기본방법

박미선

14:30~15:40

상담의 진행과정,상담자의 윤리

16:00~17:00

성격심리학 &

이상심리학

특질이론 인본주의

박준화

17:10~18:10

심리검사 이상심리 개관

18:20~19:20

이상심리학 

6

13:00~14:20

상담의유형

단기상담

박미선

14:30~15:40

집단상담,가족상담

16:00~17:00

 

이상심리학 &

사회심리학

 

이상심리학 

박준화

17:10~18:10

사회심리학 

18:20~19:20

사회심리학

 

 

 

** 지도교수 1 : 박준화 선생님

가톨릭대학교상담심리학 박사 수료

연세대학교 대학원 임상심리학 석사

건국대학교 대학원 심리학 강사

- (다인C&M 교육팀장,전문강사 역임

- () Fortune Korea 인사과 과장 역임

강의삼성전자, CJ 텔레닉스삼성생명법무연수원,

한국수자원공사듀오등

 

** 지도교수 2 : 박미선 선생님

국제신학대학원 상담심리학과 박사과정 수료

아이에듀 학습코칭상담센터 소장

국제신학대학원상담목회대학원총신대평생교육원 강의교수

) (다세움 산하 가정폭력상담소 소장

여성벤처콤플렉스 상담강사

삼성장학재단 배움터 프로젝트 강사

,고등학교 교사 및 학부모 연수 강의

한국가족상담협회 전문가

학습코칭전문가 강사

by 버려진Eye 2014. 8. 27. 13:54

Eclipse 단축키 확인 및 변경

Eclipse의 모든 단축키는 Window >> Preferences >> Workbench >> Keys 메뉴에서 확인 및 변경이 가능하다. 그 동안 다른 툴에서 자신의 손에 익숙한 단축키들이 있다면 이 메뉴에서 단축키들을 변경하는 것이 가능하다.

Java Editor 단축키

Ctrl + Shift + M : 특정 클래스 Import 시키기
Ctrl + Shift + O : 자동으로 Import 시키기
Ctrl + Shift + F : 코드 자동 정리
Ctrl + Shift + G : 특정 메써드나 필드를 Reference하고 있는 곳을 찾는다.
Ctrl + 1 : Quick Fix. 에러가 발생했을 경우 Quick Fix를 통해 쉽게 해결이 가능하다.
Ctrl + Shift + / : 블럭 주석 설정
Alt + Shift + UP : 커서를 기준으로 토큰단위 블럭지정
Alt + Shift + DOWN : 커서를 기준으로 토큰단위 블럭해제
CTRL + L : 특정 줄번호로 가기
Alt + Shift + J : 자동으로 주석 달기 (메소드나 멤버변수에 포커스 두고 실행)

Window 이동

F10 : 메뉴창을 활성화
Ctrl + F8 : 다음 Perspective로 이동
Ctrl + N : 새로운 파일 및 프로젝트 생성.
Ctrl + Shift + Down : Java Editor에서 다음 member로 이동.
Ctrl + F7 : 다음 View로 이동.
Ctrl + Shift + F7 : 이전 View로 이동.
Alt + <- : 이전 작업 화면
Alt + -> : 다음 작업 화면
F12 : 컴파일 중 에러등으로 포커스가 다른데로 갔을 때 Editor 로 커서 이동
Ctrl + 1 : 컴파일 에러가 발생한 곳에서 Ctrl + 1을 누를 경우 컴파일 에러에 대한 해결책을 제시

디버깅 단축키

CTRL + Shift + B : 현 커서의 위치에 브레이크 포인터 설정/해제
F11 : 디버깅 시작
F8 : 디버깅 계속
F6 : 한줄씩 실행(Step Over)
F5 : 한줄씩 실행하되 함수일 경우 그 함수 내부로 들어감(Step Into)
CTRL + R : 현재 라인까지 실행(Run to Line)

Refactoring 단축키

Shift + ALT + 알파벳 : Refactoring을 위한 단축키 임.

RUN 단축키

Ctrl + F11 : 이전에 실행되었던 Run파일 실행.

by 버려진Eye 2013. 3. 18. 18:20

단축키 

 설명

 Ctrl + Shift + L

 이클립스 단축키 설명 모두 보기

 Ctrl + space

 해당하는 알파벳이나 이름에 해당하는 목록들을 보여주는 자동 완성
 Alt + Shift + R 텍스트를 일괄 변경, 특정 변수의 이름을 일일히 변경하기보다 변수 하나에 커서를 두둔 후 단축키를 누르면 똑같은 변수 이름들에 테두리가 쳐지며 하나의 변경만으로 일괄적인 수정이 가능
 Ctrl + i 전체 소스를 선택 후 단축키를 누르면 놓친 들여쓰기를 한꺼번에 자동 처리
 F3 소드 위에서 누르면 해당 메소드로 이동
 Ctrl + Shift + R 파일명으로 파일 찾기, 찾아서 바로 이동 가능
 Ctrl + Shift + 위 화살표 위에 있는 메소드 선택
 Ctrl + Shift + 아래 화살표 아래에 있는 메소드 선택
 Ctrl + Alt + 위 화살표 해당 라인을 복사해서 바로 윗 라인에 붙여넣는다
 Ctrl + Alt + 아래 화살표 해당 라인을 복사해서 바로 아래 라인에 붙여넣는다
  /** + Enter 메소드 혹은 클래스 선언부 바로 위에서 누르면 주석이 자동 생성된다
 Ctrl + Shift + O

 자동으로 클래스를 import 한다. 프로젝트 막바지에 사용하지 않는 클래스 import 제거도 가능

 F11

 Debug on Server

 Ctrl + F11

 Run on Server, 실행

 F12 Editor로 포커스 이동

 

 

 

■ Eclips 단축키에 대한 아래 포스팅 참조 :  http://blog.naver.com/skylapunjel?Redirect=Log&logNo=150121253316

 

1. 단축키 확인

- Window > Preference > General > Keys 메뉴에서 확인

- 단축키 보기 Hint : Ctrl + Shift + L

 

2. 실행

Ctrl + F11 : 실행(바로 전에 실행했던 클래스(Run파일) 실행).

 

3. 디버그

1) F11 : 디버그 모드로 실행

2) F5 : step into(현재의 명령문이 호출되는 메소드 속으로 진행하여, 그 첫 문장을 실행하기 전에 멈춘다. 하지만 자바 라이브러리 클래스 수준까지 들어가므로 단계필터 사용을 체크(Shift + F5)를 하면 필터를 설정한 클래스에 대하서는 Step Over 기능과 같은 기능을 수행한다.)

3) F6 : step over(현재의 명령문을 실행하고 다음 명령문 직전에 다시 멈춘다.)

4) F8 : 멈추어 있던 쓰레드를 다시 계속 실행한다.(Resume)

5) Ctrl + Shift + B : 현재커서위치에 Break point설정 또는 해제

6) Ctrl + R : 현재 라인까지 실행(Run to Line)

Display view(표시) : Window > Show View > Other > Debug > Display를 선택하여 소스상에서 필요한 부분을 선택해서 실행시켜 볼 수 있다. 한 순간의 값만 필요할 때 볼 수 있는 반면에 아래는 계속적으로 값이 변하는 것을 확인 할 수 있다.

 

4. 소스 네비게이션

1) Ctrl + 객체클릭(혹은 F3) : 클래스나 메소드 혹은 멤버를 정의한 곳으로 이동(Open Declaration)

2) Ctrl + O : 해당 소스의 메소드 리스트를 확인하려 할때

3) F4 : 클래스명을 선택하고 누르면 해당 클래스의 Hierarchy 를 볼 수 있다.

4) F3 : 메소드 정의부로 이동

5) Alt + Shift + R : 변수 및 메소드 변경(변경할 변수 에서 단축키를 누르고 변경 후에 엔터를 누르면 변수명이 모두 변경)

 

5. 소스 편집

1) Ctrl + spacebar : 자동 완성 기능. 어휘의 자동완성(Content Assistance)

2) Ctrl + Shift + O : 자동으로 import 하기(사용하지 않는 Class는 삭제)

3) Ctrl + Shift + M : 캐럿이 위치한 대상에 필요한 특정클래스 import

4) Ctrl + Shift + G : 클래스의 메소드나 필드를 Reference하고 있는 곳으로 이동

반대 : F3 (Reference하는 클래스로 이동)

5) Shift + Alt + S R : getter/setter 자동 생성

6) Ctrl + Shift + Space : 메소드 파라미터 힌트 (메소드에 입력해야 하는 파라미터 정보가 표시된다.)

7) F2 : 에러의 원인에 대한 힌트 (에러 라인에 커서를 위치시키고...)


8) Ctrl + Shift + / : 블록 주석(/*..*/) 추가

9) Ctrl + Shift + \ : 블록 주석 제거

10) Ctrl + / : 한줄 또는 선택영역 주석처리 또는 제거(//)

11) Alt + Shift + J : 설정해 둔 기본주석 달기(JavaDoc 주석)


12) Ctrl + S : 저장 및 컴파일

13) Ctrl + Shift + F4 : 열린 파일 모두 닫기

14) Ctrl + Shift + W : 열린 파일 모두 닫기

15) Ctrl +W : 창 닫기


16) Ctrl + Q : 마지막 편집위치로 가기

17) Ctrl + L : 특정줄번호로 가기. 로컬 히스토리 기능을 이용하면 이전에 편집했던 내용으로 변환이 가능하다.

18) Ctrl + O : 현재 편집 화면의 메소드나 필드로 이동하기

19) CTRL + 휠 : 페이지 단위 이동


20) Ctrl + D : 한줄삭제


21) Ctrl + I : 들여쓰기 자동 수정

22) Ctrl + Shift + F : 소스 정리


23) Alt + Up(Down) : 위(아래)줄과 바꾸기

24) Ctrl + Alt + ↑↓(상/하) : 한줄(블럭) 복사

25) Alt + Shift + 방향키 : 블록 선택하기


26) Ctrl + M : 전체화면 토글

27) Ctrl + Z / Ctrl + Y : Undo / Redo

28) Ctrl + , or . : 이전 또는 다음 annotation(에러, 워닝, 북마크 가능)으로 점프

29) Ctrl + T : 하이어라키 팝업 창 띄우기(인터페이스 구현 클래스간 이동시 편리)

30) Ctrl + F6 (재정의 하는게 편리) : ULTRAEDIT나 EDITPLUS 의 Ctrl +TAB 과 같은 기능

31) Alt + ←→(좌/우) : 이후, 이전(뷰 화면의 탭에 열린 페이지 이동)

32) Ctrl + Shift + R : Open Resource

33) Ctrl + Shift + ↑↓(상/하) : 다음/이전 메소드로 이동

34) Ctrl + Shift + E : Switch to Editor (탭에 열려있는 Editor 이동)

35) Ctrl + Shift + G : 클래스의 메소드나 필드를 Reference하고 있는 곳으로 이동

36) Ctrl + 1 : Quick Fix(구현하지 않은 메소드 추가, 로컬 변수 이름 바꾸기, 행둘러싸기(if, while, for emd))

37) Ctrl + 2 + R : Rename(리팩토링)


6. 문자열 찾기

Ctrl + K : 찾고자 하는 문자열을 블럭으로 설정한 후 키를 누른다.

Ctrl + Shift + K : 역으로 찾고자 하는 문자열을 찾아감.

Ctrl + J : 입력하면서 찾을 수 있음.

Ctrl + Shift + J : 입력하면서 거꾸로 찾아갈 수 있음.

Ctrl + F : 기본적으로 찾기

Ctrl + H : Find 및 Replace

7. 템플릿 사용

1) sysout 입력한 후 Ctrl + Space 하면 System.out.println(); 으로 바뀐다.

2) try 입력한 후 Ctrl + Space 하면 try-catch 문이 완성된다.

3) for 입력한 후 Ctrl + Space 하면 여러가지 for 문을 완성할 수 있다.

4) 템플릿을 수정하거나 추가하려면 Window > Preference > Java > Editor > Templates 에서 할 수 있다.


8. 에디터 변환

1) 에디터가 여러 파일을 열어서 작업중일때 Ctrl + F6 키를 누르면 여러파일명이 나오고 F6키를 계속 누르면 아래로

2) Ctrl + Shift + F6 키를 누르면 위로 커서가 움직인다.

3) Ctrl + F7 : 뷰간 전환

4) Ctrl + F8 : 퍼스펙티브간 전환

5) Ctrl + E : 뷰 화면의 탭에 열린 페이지 이동

6) Ctrl + H6 : 열린 페이지 이동

7) F12 : 에디터로 포커스 위치

by 버려진Eye 2013. 3. 18. 18:20

실행

  1. Ctrl + F11 : 바로 전에 실행했던 클래스 실행

소스 네비게이션

  1. Ctrl + 마우스커서(혹은 F3) : 클래스나 메소드 혹은 멤버를 상세하게 검색하고자 할때
  2. Alt + ->, Alt + <- : 이후, 이전
  3. Ctrl + o : 해당 소스의 메소드 리스트를 확인하려 할때
  4. F4 : 클래스명을 선택하고 누르면 해당 클래스의 Hierarchy 를 볼 수 있다.

문자열 찾기

  1. Ctrl + k : 찾고자 하는 문자열을 블럭으로 설정한 후 키를 누른다.
  2. Ctrl + Shift + k : 역으로 찾고자 하는 문자열을 찾아감.
  3. Ctrl + j : 입력하면서 찾을 수 있음.
  4. Ctrl + Shift + j : 입력하면서 거꾸로 찾아갈 수 있음.
  5. Ctrl + f : 기본적으로 찾기

소스 편집

  1. Ctrl + Space : 입력 보조장치(Content Assistance) 강제 호출 => 입력하는 도중엔 언제라도 강제 호출 가능하다.
  2. F2 : 컴파일 에러의 빨간줄에 커서를 갖져다가 이 키를 누르면 에러의 원인에 대한 힌트를 제공한다.
  3. Ctrl + l : 원하는 소스 라인으로 이동
    • 로컬 히스토리 기능을 이용하면 이전에 편집했던 내용으로 변환이 가능하다.
  4. Ctrl + Shift + Space : 메소드의 가로안에 커서를 놓고 이 키를 누르면 파라미터 타입 힌트를 볼 수 있다.
  5. 한 줄 삭제 CTRL + D
  6. 파일 닫기 : CTRL+W
  7. 들여쓰기 자동 수정. (3.0 NEW) : CTRL+I
  8. 블록 주석(/*..*/) 추가.(3.0 NEW): CTRL+SHIFT+/
    • Ctrl + / 해주면 여러줄이 한꺼번에 주석처리됨. 주석 해제하려면 반대로 하면 됨.
  9. 위(아래)줄과 바꾸기 : ALT+UP(DOWN)
  10. 블록 선택하기.  : ALT+SHIFT+방향키
  11. 메소드의 파라메터 목록 보기. : CTRL+SHIFT+SPACE
  12. 자동으로 import 하기 : CTRL+SHIFT+O
  13. 열린 파일 모두 닫기 : CTRL + SHIFT + F4
  14. 블록 주석 제거 : CTRL+SHIFT+
  15. 전체화면 토글 : CTRL+M
  16. 한 줄(블럭) 복사 : Ctrl + Alt + 위(아래)
  17. 다음 annotation(에러, 워닝, 북마크 가능)으로 점프 : Ctrl + , or .
  18. 퀵 픽스 : Ctrl + 1  
  19. 메소드 정의부로 이동 : F3
  20. 하이어라키 팦업 창 띄우기(인터페이스 구현 클래스간 이동시 편리) : Ctrl + T  
  21. 메소드나 필드 이동하기 CTRL + O
  22. ULTRAEDIT나 EDITPLUS 의 CTRL+TAB 과 같은 기능. : CTRL+F6

템플릿 사용

  1. sysout 입력한 후 Ctrl + Space 하면 System.out.println(); 으로 바뀐다.
  2. try 입력한 후 Ctrl + Space 하면 try-catch 문이 완성된다.
  3. for 입력한 후 Ctrl + Space 하면 여러가지 for 문을 완성할 수 있다.
  4. 템플릿을 수정하거나 추가하려면 환경설정/자바/편집기/템플리트 에서 할 수 있다.

메소드 쉽게 생성하기

  1. 클래스의 멤버를 일단 먼저 생성한다.
  2. override 메소드를 구현하려면 : 소스->메소드대체/구현 에서 해당 메소드를 체크한다.
  3. 기타 클래스의 멤버가 클래스의 오브젝트라면 : 소스->위임메소드 생성에서 메소드를 선택한다.

Organize import

  1. 자바파일을 여러개 선택한 후 소스 -> 가져오기 체계화 해주면 모두 적용된다.

소스 코드 형식 및 공통 주석 설정

  1. 환경설정 -> 자바 -> 코드 스타일 -> 코드 포멧터 -> 가져오기 -> 프로파일.xml 을 불러다가 쓰면 된다.
  2. 또한 다수의 자바파일에 프로파일을 적용하려면 패키지 탐색기에서 패키지를 선택한 후 소스 -> 형식화를 선택하면 된다.
  3. 환경설정 -> 자바 -> 코드 스타일 -> 코드 템플리트 -> 가져오기 -> 템플리트.xml 을 불러다가 쓰면 된다.

에디터 변환

  1. 에디터가 여러 파일을 열어서 작업중일때 Ctrl + F6 키를 누르면 여러파일명이 나오고 F6키를 계속 누르면 아래로
  2. Ctrl + Shift + F6 키를 누르면 위로 커서가 움직인다.
  3. Ctrl + F7 : 뷰간 전환
  4. Ctrl + F8 : 퍼스펙티브간 전환
  5. F12 : 에디터로 포커스 위치

by 버려진Eye 2013. 3. 18. 18:20

____________CTRL Key Bound_____________
Ctrl + a - Jump to the start of the line
Ctrl + b - Move back a char
Ctrl + c - Terminate the command
Ctrl + d - Delete from under the cursor
Ctrl + e - Jump to the end of the line
Ctrl + f - Move forward a char
Ctrl + k - Delete to EOL
Ctrl + l - Clear the screen
Ctrl + r - Search the history backwards
Ctrl + R - Search the history backwards with multi occurrence
Ctrl + u - Delete backward from cursor
Ctrl + xx - Move between EOL and current cursor position
Ctrl + x @ - Show possible hostname completions
Ctrl + z - Suspend/ Stop the command

____________ALT Key Bound___________
Alt + < - Move to the first line in the history
Alt + > - Move to the last line in the history
Alt + ? - Show current completion list
Alt + * - Insert all possible completions
Alt + / - Attempt to complete filename
Alt + . - Yank last argument to previous command
Alt + b - Move backward
Alt + c - Capitalize the word
Alt + d - Delete word
Alt + f - Move forward
Alt + l - Make word lowercase
Alt + n - Search the history forwards non-incremental
Alt + p - Search the history backwards non-incremental
Alt + r - Recall command
Alt + t - Move words around
Alt + u - Make word uppercase
Alt + back-space - Delete backward from cursor

----------------More Special Keybindings-------------------

Here "2T" means Press TAB twice

2T - All available commands(common)
(string)2T - All available commands starting with (string)
/2T - Entire directory structure including Hidden one
2T - Only Sub Dirs inside including Hidden one
*2T - Only Sub Dirs inside without Hidden one 
~2T - All Present Users on system from "/etc/passwd"
$2T - All Sys variables
@2T - Entries from "/etc/hosts"
=2T - Output like ls or dir

by 버려진Eye 2013. 3. 18. 14:24

AWK

세부 기술 자료는

http://www.okpos.com/docs/gnu/gnudocs/gawk/gawk_toc.html

 

1. awk의 기본 개념

 

1) awk?

; awk란 이름은 이 유틸리티를 작성한 A.V.Aho, P.J. Weinberger, B. Kernigham의 머리글자를 따온 것

 awk는 일종의 프로그래밍 언어지만 일반적인 언어라기 보다는 주로 패턴의 검색과 조작을 주목적으로 만들어진 것이다.

② 파일의 각 라인에서 필드(field)를 인식할 수 있는 패턴 매칭 기능을 가지고 이들 필드를 자유자재로 조작 가능한 유틸리티를 작성하고자

만든 것이다.

 

2) awk의 응용분야

데이터 프로세싱리포트 작성간단한 데이터베이스 구축

 

3) awk를 이용한 작업

① 프로그래머가 자신이 작성한 프로그램의 입력 화일이 특정한 형식에 들어 맞게 이루어져 있는지 검사.

② 출력화일을 처리하여 리포트를 만들어 냄.

③ 다른 프로그램의 입력 형식에 맞게 변환하는 작업에 이용.

 

2. awk 프로그램의 구조 및 실행

 

(1) awk 프로그램의 구조

 

  1) awk ' pattern {action}

 

    pattern {action}

    .

    .

    .

    ' filenames <-----------------입력화일(예제 : students)

 

  2) awk -f parttern-action-file filenames <----- 입력화일

    awk실행 action을 가진 프로그램 file

 

(2) awk pattern

 

      패 턴 내 용

      BEGIN 입력화일을 읽어들이기 전에 옆에 제시되는 문자을 실행시키도록 한다.

      END awk가 모든 입력을 처리한 후옆에 제시되는 문장을 실행시키도록 한다.

      expression 식을 평가한 후 이 식이 참 non-zero이거나 non-null인 경우 문장을 실행한다.

      /re/ 규식과 일치하는 문자열을 포함하고 있는 라인에서 문장을 실행한다.

      compound-pattern복합패턴이라는 것으로 &&(and), ||(or) , !(not) 그리고 괄호에 의해 연결시킨 것이다.

      expression의 경우와 마찬가지로 복합 패턴도 참인 경우의 문장을 실행시킨다.

      pattern1, pattern2 이러한 패턴을 범위 패턴이라한다현재 처리되고 있는 라인이pattern1과 일치되고다음에

      따라오 는 라인 중 임의의 라인이 pattern2와 일치할 때범위 패턴은 두 라인 사이의 각 라인과 일치한다.

 

 

(3) awk의 연산자

      연 산 자 내용

      = += -= *= /= %= 배정(assignment)연산자

      + - * / % ++ -- 산술 연산자

      || && ! 논리 연산자(|| = OR, && = AND, ! = NOT)

      > >= < <= == != 비교 연산자

      v ~p 변수 V가 패턴 P에 부합되면 참

      v !~p 변수 V가 패턴 P에 부합되지 않으면 참

 

(4) 액션(Actions)

액션은 문장(statements)으로 이루어져 있다액션은 간단하게 상수 하나로 이루어질 수도 있고개행 문자나 세미콜론(;)에 의해 분리된

몇 개의 문장의 연속으로 구성될 수도 있다.

 

 

   expressions

   print expression-list

   printf(format, expression-list)

   if (expression) statement

   if (expression) statement else statement

   while (expression) statement

   for (expression; expression; expression) statement

   for (variable in array) statement

   do statement while (expression)

   break

   continue

   next

   exit

   exit expression

   {statement}

 

 

 

(5) awk에서 미리 정의된 몇가지 변수들 변 수 내 용

      FILENAME 현재 처리되고 있는 입력 파일의 이름

      FS 입력 필드 분리문자

      NR 현재 레코드()의 번호

      NF 현재 레코드()의 필드의 갯수

      OFS출력되는 필드의 분리문자

 

 

 

3. awk의 기본예제

(1) 예제 입력 파일 소개

  ① 입력화일의 이름은 students

  ② 이 파일의 각 라인은 3개의 필드로 구성(학생 성명학과명나이)

  ③ 각 필드는 공백에 의해서 분리(공백을 필드 분리자로 간주함.)

  < awk는 각 라인에서 필드를 추출해 내는 데 필드 분리자(field separator)를 사용필드 분리자는 보통 하나 이상의 공백

  문자이다.>

 

1) 입력화일 예제 students

 

  % cat students

  John,P Physics 20

  Rick,L Mechanical 21

  Jack,T electrical 23

  Larry,M Chemical 22

  Phil,R Electrical 21

  Mike,T mechanical 22

  Paul,R Chemical 23

  John,T Chemical 23

  Tony,N Chemical 22

  James,R Electrical 21

 

 

 1) (expression)에 맞는 field 프린트하기

  % awk '$3 > 22 {print $1}' students

  Jack,T

  Paul,R

  John,T

 

 

 

 2) if 문을 사용하여 조건에 맞는 line 분리하기(각 파일에 저장)

 

  step 1 : if문을 사용하는 프로그램을 awkprog1이라는 파일로 만든다.

 

    % cat awkprog1

    { if ($1 ~ /^J/) printf "%s\n", $0 > "Jfile"

    if ($1 ~ /^P/) printf "%s\n", $0 > "Pfile"}

 

  step 2 : students 입력화일에 awkpog1 프로그램 화일을 적용한다.

 

    % awk -f awkprog1 students

 

  step 3 : 결과 보기

    % cat Jfile

    John,P Physics 20

    Jack,T electrical 23

    John,T Chemical 23

    James,R Electrical 21

 

    % cat Pfile

    Phil,R Electrical 21

    Paul,R Chemical 23

 

 

 3) 평균값 구하기

 

  <프로그램 awkprog2, awkprog3>

 

  % cat awkprog2

  {sum += $3}

  END {printf "The average of the ages is %.2f\n", sum/NR}

 

  % cat awkprog3

  {sum += $3

  ++no}

  END {printf "The average of the ages is %.2f\n", sum/no}

 

  <결 과>

  % awk -f awkprog3 students

  The average of the ages is 21.80

 

 

 4) while  do문을 이용하여 평균값 구하기

 

  <프로그램 awkprog4>

  % cat awkprog4

  {if (NF > 0) {

  sum = 0

  n = 1

  while (n <= NF) {

  sum = sum + $n

  n = n+1

  }

  printf "Average is %d\n", sum/NF

  }

  else

  print}

 

  <예 제>

  % awk -f awkprog4 test

  Average is 17

  Average is 3

  Average is 25

  Average is 0

 

 

Getting Started

 

basic

 

Sample data:

Beth   4.00 0

Dan    3.75 0

Kathy  4.00 10

Mark   5.00 20

Mary   5.50 22

Susie  4.25 18

 

예제:

awk '$3 > 0 { print $1, $2, $3 }' awk.data

결과:

Kathy 4.00 10

Mark 5.00 20

Mary 5.50 22

Susie 4.25 18

 

예제:

awk '$3 > 0 { print $1, $2 * $3 }' awk.data

결과:

Kathy 40

Mark 100

Mary 121

Susie 76.5

 

 

중요:

$0 : line 전체

 

 

The structure of an AWK Program

 

pattern { action } . . . single quotes protects $ by shell and allows multi lines

 

awk '$3 == 0 { print $1 }' awk.data

awk '$3 == 0'              awk.data

awk         '{ print $1 }' awk.data

 

 

중요:

{ action } 생략  ->  default : { print $0 }

pattern 생략  ->  default : TRUE

 

 

Running an AWK program

awk 'program' file1 [file2 ...] awk 'program' # from stdin until end-of-file awk -f progfile input-files

 

Simple output

fileds, $1 $2 ..., a whole line $0

 

 

Printing every line { print } { print $0 }

 

Printing certain fields { print $1, $3}

 

중요:

built-in variable - 대문자로 표기

수치값은 모두 1부터 시작 1,2,3,...

 

 

NF : the number of fields { print NF, $1, $NF}

 

Computing and printing { print $1, $2 * $3 }

 

NR : the number of records; printing line number { print NR, $0}

 

Putting text in the output { print "total pay for", $1, "is", $2 * $3 }

 

중요:

print 문에서 ',' 를 사용하면 ' '(space)가 들어감

',' 가 없으면 앞에것에 붙어서 출력됨

 

Fancier output

 

printf(format, value1, value2 ...)

에서와 동일한 형식

 

 

예제:

{ printf("total pay for %s is $%.2f\n", $1, $2 * $3)}

 

결과:

total pay for Beth is $0.00

total pay for Dan is $0.00

total pay for Kathy is $40.00

total pay for Mark is $100.00

total pay for Mary is $121.00

total pay for Susie is $76.50

 

 

예제:

{ printf("%-8s $6.2f\n", $1, $2 * $3)}

 

결과:

Beth     $  0.00

Dan      $  0.00

Kathy    $ 40.00

Mark     $100.00

Mary     $121.00

Susie    $ 76.50

 

 

Sorting the output

awk '{printf(%6.2f %s\n", $2* $3, $0)}' awk.data | sort

 

Selection

 

finding interesting line $2 >= 5 $2 * $3 > 50 $1 == "Susie" /Susie/ # regular expression $2 >= 4 || $3 >= 20 !($2 < $4 && $3 < 20)

 

Data validation NF !=3 $2 < 3.35 $2 > 10

 

BEGIN and END

맨처음 (맨나중한번만 수행됨

 

 

예제:

BEGIN { print "NAME   RATE   HOURS "; print ""}

{print }

 

결과:

NAME   RATE   HOURS

 

Beth   4.00 0

Dan    3.75 0

Kathy  4.00 10

Mark   5.00 20

Mary   5.50 22

Susie  4.25 18

 

Computing with AWK

No declaration, 초기값은 0으로 자동 지정됨

 

 

Counting $3 > 15 { emp=emp+1 } END {print emp, " work more than 15 hours" }

 

Computing sum and average

 

예제:

{pay =pay +$2*$3}

END{

print NR, "employess"

print "total", pay

print "average", pay/NR}

 

결과:

6 employess

total 337.5

average 56.25

 

예제:

$2 > maxrate {

maxrate=$2

maxemp=$1 }

END{

print "max pay", maxrate, "for", maxemp

}

 

결과:

max pay 5.50 for Mary

 

 

String concatenation no neeed to be explicitly initialized

 

예제:

{names=names$1" " }

END{print names}

 

결과:

Beth Dan Kathy Mark Mary Susie

 

 

Built in fuction

예제:

{print $1, length($1)}

 

결과:

Beth 4

Dan 3

Kathy 5

Mark 4

Mary 4

Susie 5

 

예제:

{nc=nc+length($0)+1   # +1 CR를 위함

 nw=nw+NF

}

END {

print NR, "lines,", nw,"words,", nc,"char"}

 

결과:

6 lines, 18 words, 88 char   # wc 와 동일한 기능

 

Control-flow statements

 

if statement

 

예제:

$2 > 6{

n=n+1;

pay=pay+$2*$3}

END{

if(n>0)

   print n, "employess, total", pay,\

            "average", pay/n

else

   print "no employees"

}

 

결과:

no employees

 

 

While statement

예제:

#input amount rate years   # '#'  comment 

#output compounded values at the end of each year

{

i=1;

while(i<=$3){

  printf("\t%.2f\n",($1*(1+$2)+i));

  i=i+1;

  }

}

 

수행:

awk -f awk.p1  # 입력화일이 없으므로 standard input

100 0.6 5

 

결과:

        161.00

        162.00

        163.00

        164.00

        165.00

 

위와 동일한 기능의 for:

{

for(i=1;i<=$3;i=i+1)

  printf("\t%.2f\n",($1*(1+$2)+i));

}

 

Array

 

예제:

{ line[NR]=$0}

END{

i=NR

while(i>0){

   print line[i]

   i=i-1

   }

}

 

결과: (역순으로 인쇄)

Susie  4.25 18

Mary   5.50 22

Mark   5.00 20

Kathy  4.00 10

Dan    3.75 0

Beth   4.00 0

 

 

A handful of useful "one-liners"

 

 1. END{print NR}

 2. NR==10

 3. {print $NF}

 4. {field=$NF}

    END{print field}

 5. NF>4

 6. $NF>4

 7. {nf=nf+NF}

    END {print nf}

 8. /Beth/ {nl=nl+1}   #  line에 문자 Beth가 있으면

    END {print ln}

 9. $1>max {max=$1; maxl=$0}

    END{print max, maxl}

10. NF>0

11. length($0)>80

12. {print NF, $0}

13. {temp=$1; $1=$2;$2=temp;print}

15. {$1=NR; print}

16. {$2=""; print}

17. {for(i=NF;i>0;i=i-1) printf("%s ",$i)

     printf("\n") }

18. {sum=0

     for(i=1;i<=NF;i=i+1) sum=sum+$i

     print sum }

19. {for(i=1;i<=NF;i=i+1) sum=sum+$i }

    END{ print sum}

20. {for(i=1;i<=NF;i=i+1)

       if($i<0) $i=-$i

     print }

 

Sample data

 

USSR     8649    275    Asia

Canada    3852    25    North America

China    3705    1032    Asia

USA    3615    237    North America

Brazil    3286    134    South America

India    1267    746    Asia

Mexico    762    78    North America

France    211    55    Europe

Japan    144    120    Asia

Germany    96    61    Europe

England    94    56    Europe

 

 

Patterns

 

formats

 

BEGIN statements

END statements

expression statements

/regular expression/ statements

compound pattern statements

pattern1, pattern2 statements

 

BEGIN and END

예제:

BEGIN{

FS=" "   # FS(field separator) 지정;

         # default blank(space,tab,cr,...)

printf("%10s %6s %5s  %s\n\n",\

       "Country", "Area", "Pop", "Continent")

}

{

printf("%10s %6d %5d  %s\n", $1, $2, $3, $4)

area=area+$2

pop=pop+$3

}

END{

printf("\n%10s %6d %5d\n","Total", area, pop)

}

 

결과:

   Country   Area   Pop  Continent

 

      USSR   8649   275  Asia

    Canada   3852    25  North

     China   3705  1032  Asia

       USA   3615   237  North

    Brazil   3286   134  South

     India   1267   746  Asia

    Mexico    762    78  North

    France    211    55  Europe

     Japan    144   120  Asia

   Germany     96    61  Europe

   England     94    56  Europe

 

     Total  25681  2819

 

 

expression

 

Comparision 

 

Matching ~ (매칭되면), !~ (매칭안되면) /regexpr/, ~/regexpr/, !~/regexpr/

 

 

/Asia/   #  line Asia가 있으면 TRUE

$0 ~ /Asia/   # 바로위와 동일

$4 ~ /Asia/   # $4안에 Asia가 있으면 TRUE

$4 !~/Asia/  # $4안에 Asia가 없으면 TRUE

 

 

/regular expression/ (ref. page28-32)

 

중요:

^ : 첫글짜

$ : 마지막글짜

? : 있어도 되고 없어도 됨

+ : 1번이상 반복

* : 0번이상 반복

 

 

/^[0-9]+$/ : 숫자로만 이루어진 패턴

/^[0-9][0-9][0-9]$/ : 3자리 숫자

/^(\+|-)?[0-9]+\.?[0-9]*$/ : floating point number

/^[a-zA-A][a-zA-Z0-9]*$/ : 변수이름

/^[a-zA-Z][0-9]?$/

 

 

compound pattern

$4=="Asia" && $3 >500

$4=="Asia" || $4 =="Europe"

 

 

pattern1, pattern2

/Europe/, /Africa/   # Europe이 있으면

                     # Africa이 나올때까지(Africa포함)

FNR==1, FNR==5 { print FILENAME ":" $0}   #  file 5line씩만 출력

FNR<=5 {print FILENAME ":" $0}   # 위줄과 동일기능

  # FNR  NR과 유사하나 FNR  file이 바뀌면 reset

 

Expressions

 

Constants

String constant : "Asia", "hello, world", ""

Numeric constant : 1127, 0.707E-1, 1e6 (모든 수는 floating point 형태로 저장)

 

Variables

User-defined : function, built-in variable, field variable도 아닌 경우

Built-In Variables: FNRNF, NR...

Field Variables: $1, $2, ..., $NF, $0

예제:

     BEGIN                 { FS = OFS = "\t" }

       $4 == "North America"    { $4 = "NA"}

      $4 == "South America"    { $4 = "SA" }

                    { print }

 

 

Arithmetic Operators : +, -, *, /, % and ^

 

Comparison Operators : <, <=, ++, !=, >=, >, , !~\

예제:

             $4 ~ /Asia/

 

 

Logical Operators : &&(AND), || (OR), !(NOT)

 

Conditional Expressions : ? :

 

Assignment Operators: var = expr

예제:

        $4 == "Asia"    { pop = pop + $3, n = n + 1 }

    END        { print "Total population of the", n,

                             "Asian countries is", pop, "million." }

 

 

Increment and Decrement Operators : ++, --

 

Built-in Arithmetic Functions : 도표

예제:

     randint = int (n * rand()) + 1

 

 

String Operators : concatenation

예제:

     { print NR ":" $0}

 

 

Strings as Regular Expressions

예제:

 BEGIN {

 sign = "[+-]?"

 decimal = "[0-9]+[.]?[0-9]*"

 fraction = "[.][0-9]+"

 exponent = "([eE]" sign "[0-9]+)?"

 number = "^" sign "(" decimal "|" fraction ")" exponent "&"

        }

      $0 ~ number

 

 

예제:

        $0 ~ /(\+|-)[0-9]+/

        $0 ~ "(\\ +|-)[0-9]+"

 

 

Built-In String Functions

 

예제:

     index("banana", "an")

       returns 2

        Ex 9)

            { $1 = substr($1, 1, 3); print $0 }

 

 

Number or String ? : Automatically converted

예제:

 making string : number ""

      Ex 10)

        $1 "" == $2  

    making number : string + 0

      Ex 11)

 

 

Control-Flow Statements

 

if-else

예제:

 if (expression)

     statement1

 else

     statement

 

 

while

예제:

     {   I = 1

         while (I <= NF) {

             print $I

             I++

         }

     }

 

 

for

 

그외 : do while, break, continue, next, exit

 

Empty Statement

 

예제:

         BEGIN     { FS = "\t" }

            { for (I = 1; I <= NF && $I != ""; I++)

            ;

          if (I <= NF)

            print

        }

 

 

Arrays

 

예제:

         BEGIN    { FS = "\t" }

        { pop[$4] += $3 }

      END    { for ( name in pop )

            print name, pop[name]

        }

 

 

The delete Statement

예제:

     for (I in pop)

        delete pop[I]

 

 

The split Function

예제:

     split( "7/4/76", arr, "/")

 

              arr["1"] <- 7

          arr["2"] <- 4

 arr["3"] <- 76

 

 

Multidimensional Arrays

예제:

     for (I = 1; I <= 10; I++)

         for (j = 1; j <=10; j++)

             arr[I, j] = 0

 

 

User-Defined Functions

 

예제:

  { print max($1, max($2, $3)) }

  function max (m, n) {

        return m > n ? m : n

  }

 

 

Output

 

The Print Statement

Output Separator

예제:

  BEGIN { OFS = ":"; ORS = "\n\n" }

        { print $1, $2 }

 

 

The printf Statement

Output into Files

예제:

  $3 > 100  { print $1, $3 > "bigpop" }

  $3 <= 100 { print $1, $3 > "smallpop" }

 

 

Output into Pipes

예제:

  BEGIN { FS = "\t" }

        {pop[$4] += $3}

  END   { for (c in pop)

        printf("%15s\t%6d\n", c, pop[c]) | "sort"

      }

 

 

Closing Files and Pipes

예제:

    close("sort ")

 

Input

 

Multiline Records

예제:

  BEGIN {RS = ""; FS ="\n" }

 

 

The getline Function

예제:

  /^#include/ {

      gsub( /"/, "", $2)

  while ( getline x <$2> 0)

  print x

  next

 }

 { print }

 

Interaction with Other Programs

Making a Shell Command from an AWK Program

 

예제:

awk '{print $1}' $*

 

 

 

User-Defined Functions

 

# capitalize each word in a string

function capitalize(input,    result, words, n, i, w)

{

             result = ""

             n = split(input, words, " ")

             for (i = 1; i <= n; i++) {

                           w = words[i]

                           w = toupper(substr(w, 1, 1)) substr(w, 2)

                           if (i > 1)

                                        result = result " "

                           result = result w

             }

             return result

}

 

# main program, for testing

{ print capitalize($0) }

With this input data:

 

A test line with words and numbers like 12 on it.

This program produces:

 

A Test Line With Words And Numbers Like 12 On It.

 

 

printf Formats

 

Format specifiers for printf and sprintf have the following form:

 

%[flag][width][.precision]letter

 

The control letter is required. The format conversion control letters are as follows.

 

Character Description

c ASCII character

d Decimal integer

i Decimal integer (added in POSIX)

e Floating-point format ([-]d.precisione[+-]dd)

E Floating-point format ([-]d.precisionE[+-]dd)

f Floating-point format ([-]ddd.precision)

g e or f conversion, whichever is shortest, with trailing zeros removed

G E or f conversion, whichever is shortest, with trailing zeros removed

o Unsigned octal value

s String

x Unsigned hexadecimal number; uses a-f for 10 to 15

X Unsigned hexadecimal number; uses A-F for 10 to 15

% Literal %

 

The optional flag is one of the following.

 

Character Description

- Left-justify the formatted value within the field.

 

space Prefix positive values with a space and negative values with a minus.

 

+ Always prefix numeric values with a sign, even if the value is positive.

 

# Use an alternate form: %o has a preceding 0; %x and %X are prefixed with 0x and 0X, respectively; %e, %E, and %f always have a decimal point in the result; and %g and %G do not have trailing zeros removed.

 

0 Pad output with zeros, not spaces. This happens only when the field width is wider than the converted result.

 

 

The optional width is the minimum number of characters to output. The result will be padded to this size if it is smaller. The 0 flag causes padding with zeros; otherwise, padding is with spaces.

 

The precision is optional. Its meaning varies by control letter, as shown in this table.

 

Conversion Precision Means

%d, %i, %o The minimum number of digits to print

%u, %x, %X

%e, %E, %f The number of digits to the right of the decimal point

%g, %G The maximum number of significant digits

%s The maximum number of characters to print

 

AWK[ awt 사용법 ]

 

 

 - 화면출력 '{ print }'

 

 - 입력된 행을 자동으로 공백을 기준하여 필드 단위로 나눈다앞 필드부터 $1 $2 $3 ...

 

   ) route | grep UH | grep eth1 | awk '{ print $1 }' | grep -v "255.255.255.255"

   결과) IP만 뽑아 온다.

          192.168.1.33

          192.168.1.132

          192.168.1.3

 

 - -F: 구분문자(:)를 지정하여 나눌 수 있다.

   ) head /etc/passwd | awk -F: '{ print $1, $7 }'

   결과) :를 구분문자로 나누어 첫번째일곱번째 인자를 뽑아온다.

          root /bin/csh

          nobody

          daemon

 

각종 예제 -

 

# DHCP 동적IP할당된 IP를 얻어오기

$ /sbin/ifconfig eth0 | grep 'inet addr' | awk '{print $2}' | sed -e 's/.*://'

$ /sbin/ifconfig eth0 | /bin/grep 'addr:' | /bin/awk '{ print $2 }' | /bin/awk -F: '{ print $2 }'

  결과: 210.219.177.223

 

임시 .check_ip_allow.diff 파일에서 다른 부분(허가 되지 않은 인터넷 접속자)은 인터넷을 차단한다.

l=`/bin/grep "<" /tmp/.check_ip_allow.diff | /usr/bin/awk '{ print $2 }'`

for a in $l; do

             ipchains -D input -s $a -j ACCEPT

done

 

임시 .check_ip_allow.diff 파일에서 같은 부분(허가 되지 않은 인터넷 접속자)은 인터넷을 허가 한다. - 반복됨이 문제

l=`/bin/grep ">" /tmp/.check_ip_allow.diff | /usr/bin/awk '{ print $2 }'`

for a in $l; do

             ipchains -I input -s $a -j ACCEPT

done

----------------------------------------------------------------------

awk 한 라인으로 할수 있는 여러가지 일들!

 

원본출처: 'The AWK Programming Language'

원저자: Alfred V. Aho

             Brian W. Kernighan

             Peter J. Weinberger

편집안창선(csan@coresw.co.kr, http://genesis.yonsei.ac.kr/~kabin)

 

1. 텍스트 파일의 전체 라인수를 계산

 

 END { print NR }

 

2. 텍스트 파일의 특정번째 라인의 문자열을 프린트

 

 NR == 10

 

3. 각 라인의 맨끝 단어를 프린트

 

 { print $NF }

 

4. 마지막 입력 라인의 마지막 필드를 프린트

 

 { field = $NF }

END { print field }

 

5. 4개 이상의 필드(단어)를 가지고 있는 라인을 프린트

 

 NF > 4

 

6. 마지막 필드의 값이 4 이상인 라인을 프린트

 

 $NF > 4

 

7. 모든 입력 라인에서의 총 필드의 갯수를 구함

 

 { nf = nf + NF }

 END { print nf }

 

8. 'fly'를 포함하고 있는 라인의 총수 계산

 

 /fly/ { nlines = nlines + 1 }

 END { print nlines }

 

9. 가장 긴 첫번째 필드(단어)와 그 해당 라인을 출력

 

 $1 > max { max = $1; maxline = $0 }

 END       { print max, maxline }

 

10. 적어도 한 필드(단어)를 포함하고 있는 모든 라인을 프린트

 

 NF > 0

 

11. 80문자 이상을 가진 모든 라인을 프린트

 

 length($0) > 80

 

12. 필드의 갯수와 해당 라인을 프린트

 

 { print NF, $0 }

 

13. 첫번째 두 필드를 반대로 프린트

 

 { print $2, $1 }

 

14. 첫번째 두 필드를 반대로 바꾼 다음그 라인을 프린트

 

 { temp = $1; $1 = $2; $2 = temp; print }

 

15. 첫번째 필드는 라인 번호로 대체하여 그 라인을 프린트

 

 { $1 = NR; print }

 

16. 두번째 필드는 삭제한 후 라인을 프린트

 

 { $2=""; print }

 

17. 각 라인의 모든 필드를 역순으로 프린트

 

 { for (i=NF; i> 0; i = i-1) printf("%s ", $i)

             printf("\n")

 }

 

18. 각각의 라인에 대하여 각 필드를 더한 값을 프린트

 

 { sum=0

   for (i=1;i<=NF;i=i+1) sum=sum+$i

   print sum

 }

 

19. 모든 라인에 존재하는 필드를 모두 더한 값을 프린트

 

 { for (i=1;i<=NF;i=i+1) sum=sum+$i }

 END { print sum }

 

20. 모든 라인에 대하여 각 필드의 절대값을 그 필드로 교체하여 그 라인을 프린트

 

 { for (i=1;i<=NF;i=i+1) if($i < 0) $i=-$i

   print

 }

 

 

AWK system variable

 

awk       FILENAME           현재파일명

             FS                       필드 구분자

             NF                      현재라인의 필드 수

             NR                      현재라인의 레코드 번호

             OFMT                 숫자 출력을 위한 포맷(예를 들어  %.6g)

             OFS                    출력 필드 구분자(디폴트는 blank)

             ORS                    출력 레코드 구분자(디폴트는 newline)

             RS                       레코드 구분자(디폴트는 newline)

             $0                       전체 입력라인

             $n                       n번째 필드의 내용(각 필드는 FS로 구분된다.)

 

nawk     ARGC                  명령라인의 아규먼트 수

             ARGV                  명령라인의 배열

             ENVIRON                          환경변수배열

             FNR                    NR과 같다그러나 현재 파일과 관련이 있다.

             RSTART              match함수에 의해 매치된 문자열에서의 첫번째 위치

             RLENGTH                         match함수에 의해 매치된 문자열의 길이

             SUBSEP              배열 서브스크립트를 위한 문자구분자(디폴트는 \034)

 

AWK 명령들

 

수치연산

 

atan2     atan2(y,x)

cos       cos(x)

exp        exp(arg)

int          int(arg)

log         log(arg)

rand       rand()

sin         sin(x)

sqrt       sqrt(arg)

srand     srand(expr)

 

문자열연산

 

gsub      gsub(r,s[,t])

index     index(str,substr)

length    length(arg)

match    match(s,r)

split       split(string,array[,sep])

sub        sub(r,s[,t])

substr   substr(string,m[,n])

tolower  tolower(str)

toupper toupper(str)

 

제어문

 

break

continue

do/while

exit

for

if

return

while

 

입출력/프로세스

 

close     close(filename-expr)

delete    delete array[element]

getline   getline [var][<file]

next       next

print       print [args][destination]

printf      printf format [, expression(s)][destination]

sprintf    sprintf (format [,expression(s)])

system  system(command)

 

[출처] AWK 기술 자료|작성자 몽크


by 버려진Eye 2013. 3. 15. 17:00

$ cheat bash

  !! - Last command
  !foo - Run most recent command starting with 'foo...' (ex. !ps, !mysqladmin)
  !foo:p - Print command that !foo would run, and add it as the latest to
  command history
  !$ - Last 'word' of last command ('/path/to/file' in the command 'ls -lAFh
  /path/to/file', '-uroot' in 'mysql -uroot')
  !$:p - Print word that !$ would substitute
  !* - All but first word of last command ('-lAFh /path/to/file' in the command
  'ls -lAFh /path/to/file', '-uroot' in 'mysql -uroot')
  !*:p - Print words that !* would substitute

  ^foo^bar - Replace 'foo' in last command with 'bar', print the result, then
  run. ('mysqladmni -uroot', run '^ni^in', results in 'mysqladmin -uroot')

  {a,b,c} passes words to the command, substituting a, b, and c sequentially
  (`cp file{,.bk}` runs `cp file file.bk`)

  Ctrl + a - Jump to the start of the line
  Ctrl + b - Move back a char
  Ctrl + c - Terminate the command
  Ctrl + d - Delete from under the cursor
  Ctrl + e - Jump to the end of the line
  Ctrl + f - Move forward a char
  Ctrl + k - Delete to EOL
  Ctrl + l - Clear the screen
  Ctrl + r - Search the history backwards
  Ctrl + R - Search the history backwards with multi occurrence
  Ctrl + t - Transpose the current char with the previous
  Ctrl + u - Delete backward from cursor
  Ctrl + w - Delete backward a word
  Ctrl + xx - Move between EOL and current cursor position
  Ctrl + x @ - Show possible hostname completions
  Ctrl + z - Suspend/ Stop the command
  Ctrl + x; Ctrl + e - Edit line into your favorite editor

  Alt + < - Move to the first line in the history
  Alt + > - Move to the last line in the history
  Alt + ? - Show current completion list
  Alt + * - Insert all possible completions
  Alt + / - Attempt to complete filename
  Alt + . - Yank last argument to previous command
  Alt + b - Move backward
  Alt + c - Capitalize the word
  Alt + d - Delete word
  Alt + f - Move forward
  Alt + l - Make word lowercase
  Alt + n - Search the history forwards non-incremental
  Alt + p - Search the history backwards non-incremental
  Alt + r - Recall command
  Alt + t - Transpose the current word with the previous
  Alt + u - Make word uppercase
  Alt + back-space - Delete backward from cursor

  (Here "2T" means Press TAB twice)
  $ 2T - All available commands(common)
  $ (string)2T - All available commands starting with (string)
  $ /2T - Entire directory structure including Hidden one
  $ (dir)2T - Only Sub Dirs inside (dir) including Hidden one
  $ *2T - Only Sub Dirs inside without Hidden one 
  $ ~2T - All Present Users on system from "/etc/passwd"
  $ $2T - All Sys variables
  $ @2T - Entries from "/etc/hosts"
  $ =2T - Output like ls or dir
  .bash_profile = sourced by login shell, 
  .bashrc = sourced by all shells, 
  .bash_aliases = should be sourced by .bashrc

Run something:
  for i in a b c; do $i 'hello'; done

Do something on a bunch of files:
  for i in *.rb; do echo "$i"; done

If syntax:
  if [[ -e .ssh ]]; then echo "hi"; fi

Numerical comparison:
  i=0; if (( i <= 1 )); then echo "smaller or equal"; else echo "bigger"; fi

file check flags:
  -e:  file exists
  -f:  regular file (non directory)
  -d:  directory
  -s:  non-zero file
  -x:  execute permission

Avoid duplicates in your history:
  export HISTIGNORE="&:ls:ls *:[bf]g:exit"


by 버려진Eye 2012. 11. 12. 01:32

Linux / Unix Command: history

NAME

history - GNU History Library

DESCRIPTION

Many programs read input from the user a line at a time. The GNU History library is able to keep track of those lines, associate arbitrary data with each line, and utilize information from previous lines in composing new ones.

HISTORY EXPANSION

The history library supports a history expansion feature that is identical to the history expansion in bash. This section describes what syntax features are available.

History expansions introduce words from the history list into the input stream, making it easy to repeat commands, insert the arguments to a previous command into the current input line, or fix errors in previous commands quickly.

History expansion is usually performed immediately after a complete line is read. It takes place in two parts. The first is to determine which line from the history list to use during substitution. The second is to select portions of that line for inclusion into the current one. The line selected from the history is the event, and the portions of that line that are acted upon are words. Various modifiers are available to manipulate the selected words. The line is broken into words in the same fashion as bash does when reading input, so that several words that would otherwise be separated are considered one word when surrounded by quotes (see the description of history_tokenize() below). History expansions are introduced by the appearance of the history expansion character, which is ! by default. Only backslash (\) and single quotes can quote the history expansion character.

Event Designators

An event designator is a reference to a command line entry in the history list.

!
Start a history substitution, except when followed by a blank, newline, = or (.
!n
Refer to command line n.
!-n
Refer to the current command line minus n.
!!
Refer to the previous command. This is a synonym for `!-1'.
!string
Refer to the most recent command starting with string.
!?string[?]
Refer to the most recent command containing string. The trailing ? may be omitted ifstring is followed immediately by a newline.
^string1^string2^
Quick substitution. Repeat the last command, replacing string1 with string2. Equivalent to ``!!:s/string1/string2/'' (see Modifiers below).
!#
The entire command line typed so far.

Word Designators

Word designators are used to select desired words from the event. A : separates the event specification from the word designator. It may be omitted if the word designator begins with a^$*-, or %. Words are numbered from the beginning of the line, with the first word being denoted by 0 (zero). Words are inserted into the current line separated by single spaces.

0 (zero)
The zeroth word. For the shell, this is the command word.
n
The nth word.
^
The first argument. That is, word 1.
$
The last argument.
%
The word matched by the most recent `?string?' search.
x-y
A range of words; `-y' abbreviates `0-y'.
*
All of the words but the zeroth. This is a synonym for `1-$'. It is not an error to use * if there is just one word in the event; the empty string is returned in that case.
x*
Abbreviates x-$.
x-
Abbreviates x-$ like x*, but omits the last word.

If a word designator is supplied without an event specification, the previous command is used as the event.

Modifiers

After the optional word designator, there may appear a sequence of one or more of the following modifiers, each preceded by a `:'.

h
Remove a trailing file name component, leaving only the head.
t
Remove all leading file name components, leaving the tail.
r
Remove a trailing suffix of the form .xxx, leaving the basename.
e
Remove all but the trailing suffix.
p
Print the new command but do not execute it.
q
Quote the substituted words, escaping further substitutions.
x
Quote the substituted words as with q, but break into words at blanks and newlines.
s/old/new/
Substitute new for the first occurrence of old in the event line. Any delimiter can be used in place of /. The final delimiter is optional if it is the last character of the event line. The delimiter may be quoted in old and new with a single backslash. If & appears in new, it is replaced by old. A single backslash will quote the &. If old is null, it is set to the last oldsubstituted, or, if no previous history substitutions took place, the last string in a!?string[?] search.
&
Repeat the previous substitution.
g
Cause changes to be applied over the entire event line. This is used in conjunction with `:s' (e.g., `:gs/old/new/') or `:&'. If used with `:s', any delimiter can be used in place of /, and the final delimiter is optional if it is the last character of the event line.

PROGRAMMING WITH HISTORY FUNCTIONS

This section describes how to use the History library in other programs.

Introduction to History

The programmer using the History library has available functions for remembering lines on a history list, associating arbitrary data with a line, removing lines from the list, searching through the list for a line containing an arbitrary text string, and referencing any line in the list directly. In addition, a history expansion function is available which provides for a consistent user interface across different programs.

The user using programs written with the History library has the benefit of a consistent user interface with a set of well-known commands for manipulating the text of previous lines and using that text in new commands. The basic history manipulation commands are identical to the history substitution provided by bash.

If the programmer desires, he can use the Readline library, which includes some history manipulation by default, and has the added advantage of command line editing.

Before declaring any functions using any functionality the History library provides in other code, an application writer should include the file <readline/history.h> in any file that uses the History library's features. It supplies extern declarations for all of the library's public functions and variables, and declares all of the public data structures.

History Storage

The history list is an array of history entries. A history entry is declared as follows:

typedef void * histdata_t; 

typedef struct _hist_entry {
  char *line;
  histdata_t data;
} HIST_ENTRY;

The history list itself might therefore be declared as

HIST_ENTRY ** the_history_list; 

The state of the History library is encapsulated into a single structure:

/*
 * A structure used to pass around the current state of the history.
 */
typedef struct _hist_state {
  HIST_ENTRY **entries; /* Pointer to the entries themselves. */
  int offset;           /* The location pointer within this array. */
  int length;           /* Number of elements within this array. */
  int size;             /* Number of slots allocated to this array. */
  int flags;
} HISTORY_STATE;

If the flags member includes HS_STIFLED, the history has been stifled.

History Functions

This section describes the calling sequence for the various functions exported by the GNU History library.

Initializing History and State Management

This section describes functions used to initialize and manage the state of the History library when you want to use the history functions in your program.

1 void (using_history, void, 
Begin a session in which the history functions might be used. This initializes the interactive variables.

1 HISTORY_STATE * (history_get_history_state, void, 
Return a structure describing the current state of the input history.

1 void (history_set_history_state, HISTORY_STATE *state, 
Set the state of the history list according to state.

History List Management

These functions manage individual entries on the history list, or set parameters managing the list itself.

1 void (add_history, const char *string, 
Place string at the end of the history list. The associated data field (if any) is set to NULL.

1 HIST_ENTRY * (remove_history, int which, 
Remove history entry at offset which from the history. The removed element is returned so you can free the line, data, and containing structure.

3 HIST_ENTRY * (replace_history_entry, int which, const char *line
Make the history entry at offset which have line and data. This returns the old entry so you can dispose of the data. In the case of an invalid which, a NULL pointer is returned.

1 void (clear_history, void, 
Clear the history list by deleting all the entries.

1 void (stifle_history, int max, 
Stifle the history list, remembering only the last max entries.

1 int (unstifle_history, void, 
Stop stifling the history. This returns the previously-set maximum number of history entries (as set by stifle_history()). history was stifled. The value is positive if the history was stifled, negative if it wasn't.

1 int (history_is_stifled, void, 
Returns non-zero if the history is stifled, zero if it is not.

Information About the History List

These functions return information about the entire history list or individual list entries.

1 HIST_ENTRY ** (history_list, void, 
Return a NULL terminated array of HIST_ENTRY * which is the current input history. Element 0 of this list is the beginning of time. If there is no history, return NULL.

1 int (where_history, void, 
Returns the offset of the current history element.

1 HIST_ENTRY * (current_history, void, 
Return the history entry at the current position, as determined by where_history(). If there is no entry there, return a NULL pointer.

1 HIST_ENTRY * (history_get, int offset, 
Return the history entry at position offset, starting from history_base. If there is no entry there, or if offset is greater than the history length, return a NULL pointer.

1 int (history_total_bytes, void, 
Return the number of bytes that the primary history entries are using. This function returns the sum of the lengths of all the lines in the history.

Moving Around the History List

These functions allow the current index into the history list to be set or changed.

1 int (history_set_pos, int pos, 
Set the current history offset to pos, an absolute index into the list. Returns 1 on success, 0 ifpos is less than zero or greater than the number of history entries.

1 HIST_ENTRY * (previous_history, void, 
Back up the current history offset to the previous history entry, and return a pointer to that entry. If there is no previous entry, return a NULL pointer.

1 HIST_ENTRY * (next_history, void, 
Move the current history offset forward to the next history entry, and return the a pointer to that entry. If there is no next entry, return a NULL pointer.

Searching the History List

These functions allow searching of the history list for entries containing a specific string. Searching may be performed both forward and backward from the current history position. The search may be anchored, meaning that the string must match at the beginning of the history entry.

2 int (history_search, const char *string, int direction
Search the history for string, starting at the current history offset. If direction is less than 0, then the search is through previous entries, otherwise through subsequent entries. If string is found, then the current history index is set to that history entry, and the value returned is the offset in the line of the entry where string was found. Otherwise, nothing is changed, and a -1 is returned.

2 int (history_search_prefix, const char *string, int direction
Search the history for string, starting at the current history offset. The search is anchored: matching lines must begin with string. If direction is less than 0, then the search is through previous entries, otherwise through subsequent entries. If string is found, then the current history index is set to that entry, and the return value is 0. Otherwise, nothing is changed, and a -1 is returned.

3 int (history_search_pos, const char *string, int direction
Search for string in the history list, starting at pos, an absolute index into the list. If direction is negative, the search proceeds backward from pos, otherwise forward. Returns the absolute index of the history element where string was found, or -1 otherwise.

Managing the History File

The History library can read the history from and write it to a file. This section documents the functions for managing a history file.

1 int (read_history, const char *filename, 
Add the contents of filename to the history list, a line at a time. If filename is NULL, then read from ~/.history. Returns 0 if successful, or errno if not.

3 int (read_history_range, const char *filename, int from
Read a range of lines from filename, adding them to the history list. Start reading at line fromand end at to. If from is zero, start at the beginning. If to is less than from, then read until the end of the file. If filename is NULL, then read from ~/.history. Returns 0 if successful, or errnoif not.

1 int (write_history, const char *filename, 
Write the current history to filename, overwriting filename if necessary. If filename is NULL, then write the history list to ~/.history. Returns 0 on success, or errno on a read or write error.

2 int (append_history, int nelements, const char *filename
Append the last nelements of the history list to filename. If filename is NULL, then append to~/.history. Returns 0 on success, or errno on a read or write error.

2 int (history_truncate_file, const char *filename, int nlines
Truncate the history file filename, leaving only the last nlines lines. If filename is NULL, then~/.history is truncated. Returns 0 on success, or errno on failure.

History Expansion

These functions implement history expansion.

2 int (history_expand, char *string, char **output
Expand string, placing the result into output, a pointer to a string. Returns:

0
If no expansions took place (or, if the only change in the text was the removal of escape characters preceding the history expansion character);
1
if expansions did take place;
-1
if there was an error in expansion;
2
if the returned line should be displayed, but not executed, as with the :p modifier.
If an error ocurred in expansion, then output contains a descriptive error message.

3 char * (get_history_event, const char *string, int *cindex
Returns the text of the history event beginning at string + *cindex*cindex is modified to point to after the event specifier. At function entry, cindex points to the index into string where the history event specification begins. qchar is a character that is allowed to end the event specification in addition to the ``normal'' terminating characters.

1 char ** (history_tokenize, const char *string, 
Return an array of tokens parsed out of string, much as the shell might. The tokens are split on the characters in the history_word_delimiters variable, and shell quoting conventions are obeyed.

3 char * (history_arg_extract, int first, int last
Extract a string segment consisting of the first through last arguments present in string. Arguments are split using history_tokenize().

History Variables

This section describes the externally-visible variables exported by the GNU History Library.

int history_base 
The logical offset of the first entry in the history list.

int history_length 
The number of entries currently stored in the history list.

int history_max_entries 
The maximum number of history entries. This must be changed using stifle_history().

char history_expansion_char 
The character that introduces a history event. The default is !. Setting this to 0 inhibits history expansion.

char history_subst_char 
The character that invokes word substitution if found at the start of a line. The default is ^.

char history_comment_char 
During tokenization, if this character is seen as the first character of a word, then it and all subsequent characters up to a newline are ignored, suppressing history expansion for the remainder of the line. This is disabled by default.

char * history_word_delimiters 
The characters that separate tokens for history_tokenize(). The default value is " \t\n()<>;&|".

char * history_no_expand_chars 
The list of characters which inhibit history expansion if found immediately followinghistory_expansion_char. The default is space, tab, newline, \r, and =.

char * history_search_delimiter_chars 
The list of additional characters which can delimit a history search string, in addition to space, tab, : and ? in the case of a substring search. The default is empty.

int history_quotes_inhibit_expansion 
If non-zero, single-quoted words are not scanned for the history expansion character. The default value is 0.

rl_linebuf_func_t * history_inhibit_expansion_function 
This should be set to the address of a function that takes two arguments: a char * (string) and an int index into that string (i). It should return a non-zero value if the history expansion starting at string[i] should not be performed; zero if the expansion should be done. It is intended for use by applications like bash that use the history expansion character for additional purposes. By default, this variable is set to NULL.

SEE ALSO

The Gnu Readline Library, Brian Fox and Chet Ramey
The Gnu History Library, Brian Fox and Chet Ramey
bash(1)
readline(3)

by 버려진Eye 2012. 11. 12. 01:16
by 버려진Eye 2012. 9. 24. 10:15
| 1 2 3 4 5 |