[AIX 운영 체제와 장치 관리 18] 운영 체제 파일 — 파일 종류·이름·경로·와일드카드, rm·mv·cp·find·file·pg·more·cat·grep·sort·diff·wc·head·tail·cut·paste·nl·colrm
https://archive.horanglab.com/posts/aix-osdev-18
핵심 정리
- 파일은 정규(텍스트·바이너리), 디렉터리, 특수(FIFO·블록·문자) 세 가지입니다. 텍스트 파일은 NUL이 없고 줄이
{LINE_MAX}바이트를 넘지 않는다는 점만 바이너리와 다릅니다. - 파일 이름은 255자까지, 대소문자를 가리며 점으로 시작하면 숨겨집니다. 경로 이름은 1023자를 넘을 수 없습니다.
*는 0개 이상의 아무 문자,?는 한 문자,[ ]는 지정 문자·범위([0-9],[[:lower:]]),[!a]는 부정입니다.cp -R은 특수 파일을 다시 만들고-r은 정규 파일로 복사하려 합니다.mv는-i없이 덮어쓰며-f와-i를 함께 주면 나중 것이 이깁니다.find -perm 0600은 정확히 일치,-perm -0600은 그 권한을 포함하는 파일을 찾습니다.tail -f로 파일 증가를 따라가고,paste - - - -로 표준 입력을 4열로 만듭니다.
| 항목 | 내용 |
|---|---|
| 버전 | AIX 6.1 (5.3판과 거의 같음) |
| 원문 | Operating system and device management — 5.3판 343356쪽, 6.1판 181194쪽 |
| 관련 명령어 | rm, mv, cp, find, file, pg, more, cat, grep, sort, diff, wc, head, tail, cut, paste, nl, colrm |
| 관련 파일 | /etc/magic, /etc/passwd |
운영 체제에서는 소프트웨어와 하드웨어 접근을 표준화하려고 정보의 모든 입력과 출력(I/O)에 파일을 씁니다.
입력은 파일 내용이 바뀌거나 파일에 쓸 때 일어납니다. 출력은 한 파일의 내용을 읽거나 다른 파일로 옮길 때 일어납니다. 예를 들어 파일을 인쇄하면 시스템은 텍스트 파일에서 정보를 읽어 프린터를 나타내는 파일에 씁니다.
영어 원문
Operating system files
Files are used for all input and output (I/O) of information in the operating system, to standardize access to both software and hardware.
Input occurs when the contents of a file is modified or written to. Output occurs when the contents of one file is read or transferred to another file. For example, to create a printed copy of a file, the system reads the information from the text file and writes that information to the file representing the printer.
파일 종류
시스템이 인식하는 파일 종류는 정규, 디렉터리, 특수 가운데 하나입니다. 그러나 운영 체제는 이 기본 종류의 여러 변형을 씁니다.
기본 파일 종류는 다음과 같습니다.
| 종류 | 설명 |
|---|---|
| 정규(regular) | 데이터(텍스트, 바이너리, 실행 파일)를 저장합니다. |
| 디렉터리(directory) | 다른 파일에 접근하는 데 쓰는 정보를 담습니다. |
| 특수(special) | FIFO(선입선출) 파이프 파일이나 물리 장치를 정의합니다. |
시스템이 인식하는 모든 파일 종류는 이 범주 가운데 하나에 듭니다. 그러나 운영 체제는 이 기본 종류의 여러 변형을 씁니다.
정규 파일
정규 파일은 가장 흔한 파일로 데이터를 담는 데 씁니다. 정규 파일은 텍스트 파일이나 바이너리 파일입니다.
텍스트 파일
텍스트 파일은 ASCII 형식 텍스트로 저장한 정보를 담고 사용자가 읽을 수 있는 정규 파일입니다. 이 파일은 화면에 보이거나 인쇄할 수 있습니다. 텍스트 파일의 줄에는 NUL 문자가 없어야 하며, 줄 바꿈 문자를 포함해 어느 줄도 {LINE_MAX} 바이트를 넘을 수 없습니다.
텍스트 파일이라는 말이 제어 문자나 다른 출력할 수 없는 문자(NUL 제외)를 넣지 못하게 하는 것은 아닙니다. 그래서 텍스트 파일을 입력이나 출력으로 다루는 표준 유틸리티는 특수 문자를 처리할 수 있거나, 각 설명에서 그 한계를 명시합니다.
바이너리 파일
바이너리 파일은 컴퓨터가 읽을 수 있는 정보를 담은 정규 파일입니다. 바이너리 파일은 시스템에 작업을 시키는 실행 파일일 수 있습니다. 명령과 프로그램은 실행 가능한 바이너리 파일로 저장됩니다. 특수 컴파일 프로그램이 ASCII 텍스트를 바이너리 코드로 번역합니다.
텍스트 파일과 바이너리 파일의 차이는, 텍스트 파일은 줄이 {LINE_MAX} 바이트보다 짧고 NUL 문자가 없으며 각 줄이 줄 바꿈 문자로 끝난다는 점뿐입니다.
디렉터리 파일
디렉터리 파일은 시스템이 모든 종류의 파일에 접근하는 데 필요한 정보를 담지만 실제 파일 데이터는 담지 않습니다. 그래서 디렉터리는 정규 파일보다 공간을 덜 차지하며 파일 시스템 구조에 유연성과 깊이를 줍니다. 디렉터리 항목 하나는 파일이나 하위 디렉터리 하나를 나타냅니다. 각 항목에는 파일 이름과 파일의 색인 노드 참조 번호(i-node 번호)가 들어 있습니다. i-node 번호는 파일에 할당된 고유한 색인 노드를 가리킵니다. i-node 번호는 파일과 관련된 데이터의 위치를 나타냅니다. 디렉터리는 별도의 명령 묶음으로 만들고 제어합니다.
특수 파일
특수 파일은 시스템의 장치를 정의하거나 프로세스가 만든 임시 파일입니다. 특수 파일의 기본 종류는 FIFO(선입선출), 블록, 문자입니다. FIFO 파일은 파이프라고도 합니다. 파이프는 한 프로세스가 다른 프로세스와 잠시 통신하려고 만듭니다. 첫 프로세스가 끝나면 이 파일은 사라집니다. 블록과 문자 파일은 장치를 정의합니다.
모든 파일에는 누가 파일을 읽고 고치고 실행할 수 있는지 정하는 권한(접근 모드라고 함) 묶음이 있습니다.
관련 개념
- 파일과 디렉터리 접근 모드 — 모든 파일에는 소유자가 있습니다. 새 파일은 만든 사용자가 소유자입니다. 소유자는 파일에 접근 모드를 지정하며, 접근 모드는 다른 사용자에게 파일 읽기·수정·실행 권한을 줍니다. 파일 소유자나 root 권한 사용자만 파일의 접근 모드를 바꿀 수 있습니다.
파일 이름 규칙
각 파일의 이름은 그 파일이 저장된 디렉터리 안에서 고유해야 합니다. 그래야 파일 시스템에서 파일의 경로 이름도 고유해집니다.
파일 이름 지침은 다음과 같습니다.
- 파일 이름은 255자까지 쓸 수 있으며 문자, 숫자, 밑줄을 넣을 수 있습니다.
- 운영 체제는 대소문자를 가리므로 파일 이름의 대문자와 소문자를 구분합니다. 그래서
FILEA,FiLea,filea는 같은 디렉터리에 있어도 서로 다른 세 파일 이름입니다. - 파일 이름은 되도록 내용을 잘 설명하고 뜻이 분명해야 합니다.
- 디렉터리도 파일과 같은 이름 규칙을 따릅니다.
- 어떤 문자는 운영 체제에 특별한 뜻이 있습니다. 파일 이름에 이 문자를 쓰지 않습니다. 다음과 같은 문자입니다.
/ \ " ’ * ; - ? [ ] ( ) ~ ! $ { } < > # @ & | space tab newline
- 점(
.)으로 시작하는 파일 이름은 일반 디렉터리 목록에서 숨겨집니다. ls 명령에-a플래그를 주면 숨김 파일도 정규 파일·디렉터리와 함께 나열됩니다.
파일 경로 이름
파일 시스템에 있는 각 파일과 디렉터리의 경로 이름은 트리 구조에서 그 앞에 오는 모든 디렉터리 이름으로 이루어집니다.
파일 시스템의 모든 경로는 /(root) 디렉터리에서 출발하므로, 파일 시스템의 각 파일은 루트 디렉터리와 고유한 관계를 가지며 이를 절대 경로 이름이라고 합니다. 절대 경로 이름은 슬래시(/) 기호로 시작합니다. 예를 들어 파일 h의 절대 경로 이름은 /B/C/h일 수 있습니다. 시스템에 h라는 파일이 두 개 있을 수 있다는 점에 주의합니다. 두 파일의 절대 경로 /B/h와 /B/C/h가 다르므로 h라는 각 파일은 시스템 안에서 고유한 이름을 가집니다. 경로 이름의 구성 요소는 마지막을 빼고 모두 디렉터리입니다. 경로 이름의 마지막 구성 요소는 파일 이름일 수 있습니다.
참고: 경로 이름은 1023자를 넘을 수 없습니다.
와일드카드와 메타 문자를 쓰는 패턴 일치
와일드카드 문자로 여러 파일 이름이나 디렉터리 이름을 편하게 지정할 수 있습니다.
와일드카드 문자는 별표(*)와 물음표(?)입니다. 메타 문자는 여는 대괄호와 닫는 대괄호([ ]), 하이픈(-), 느낌표(!)입니다.
* 와일드카드 문자를 쓰는 패턴 일치
별표(*)는 어떤 문자열과도 일치합니다.
*는 문자가 하나도 없는 경우를 포함해 어떤 문자든 뜻합니다.
다음 예를 봅니다.
- 디렉터리에 다음 파일이 있고
1test 2test afile1 afile2 bfile1 file file1 file10 file2 file3
file로 시작하는 파일만 가리키려면 다음을 씁니다.
file*
선택되는 파일은 file, file1, file10, file2, file3입니다.
- 이름에
file이라는 단어가 든 파일만 가리키려면 다음을 씁니다.
*file*
선택되는 파일은 afile1, afile2, bfile1, file, file1, file10, file2, file3입니다.
? 와일드카드 문자를 쓰는 패턴 일치
?는 아무 한 문자와 일치합니다.
?는 아무 한 문자를 뜻합니다. 다음 예를 봅니다.
- file로 시작하고 한 문자로 끝나는 파일만 가리키려면 다음을 씁니다.
file?
선택되는 파일은 file1, file2, file3입니다.
- file로 시작하고 아무 두 문자로 끝나는 파일만 가리키려면 다음을 씁니다.
file??
선택되는 파일은 file10입니다.
[ ] 셸 메타 문자를 쓰는 패턴 일치
메타 문자는 원하는 문자를 [ ]로 감싸는 또 다른 와일드카드 표기입니다. ?를 쓰는 것과 비슷하지만 일치시킬 특정 문자를 고를 수 있습니다.
[ ] 안에서는 하이픈(-)으로 값의 범위도 지정할 수 있습니다. 알파벳의 모든 문자를 지정하려면 [[:alpha:]]를, 모든 소문자를 지정하려면 [[:lower:]]를 씁니다.
다음 예를 봅니다.
1이나2로 끝나는 파일만 가리키려면 다음을 씁니다.
*file[12]
선택되는 파일은 afile1, afile2, file1, file2입니다.
- 숫자로 시작하는 파일만 가리키려면 다음을 씁니다.
[0123456789]* or [0-9]*
선택되는 파일은 1test와 2test입니다.
a로 시작하지 않는 파일만 가리키려면 다음을 씁니다.
[!a]*
선택되는 파일은 1test, 2test, bfile1, file, file1, file10, file2, file3입니다.
패턴 일치와 정규식의 차이
정규식은 문자열 집합에서 특정 문자열을 고를 수 있게 합니다. 정규식은 대개 텍스트 처리와 관련해 씁니다.
정규식은 아주 다양한 문자열을 나타낼 수 있습니다. 많은 정규식이 현재 로케일에 따라 다르게 해석될 수 있지만, 국제화 기능이 로케일 사이에서 문맥상 같은 뜻을 유지하게 해 줍니다.
다음 비교의 예를 봅니다.
Pattern Matching Regular Expression
* .*
? .
[!a] [^a]
[abc] [abc]
[[:alpha:]] [[:alpha:]]
전체 구문은 Commands Reference, Volume 1의 awk 명령을 봅니다.
영어 원문
Types of files
The types of files recognized by the system are either regular, directory, or special. However, the operating system uses many variations of these basic types.
The following basic types of files exist:
- regular — Stores data (text, binary, and executable)
- directory — Contains information used to access other files
- special — Defines a FIFO (first-in, first-out) pipe file or a physical device
All file types recognized by the system fall into one of these categories. However, the operating system uses many variations of these basic types.
Regular files
Regular files are the most common files and are used to contain data. Regular files are in the form of text files or binary files:
Text files
Text files are regular files that contain information stored in ASCII format text and are readable by the user. You can display and print these files. The lines of a text file must not contain NUL characters, and none can exceed {LINE_MAX} bytes in length, including the newline character.
The term text file does not prevent the inclusion of control or other nonprintable characters (other than NUL). Therefore, standard utilities that list text files as inputs or outputs are either able to process the special characters or they explicitly describe their limitations within their individual sections.
Binary files
Binary files are regular files that contain information readable by the computer. Binary files might be executable files that instruct the system to accomplish a job. Commands and programs are stored in executable, binary files. Special compiling programs translate ASCII text into binary code.
Text and binary files differ only in that text files have lines of less than {LINE_MAX} bytes, with no NUL characters, each terminated by a newline character.
Directory files
Directory files contain information that the system needs to access all types of files, but directory files do not contain the actual file data. As a result, directories occupy less space than a regular file and give the file system structure flexibility and depth. Each directory entry represents either a file or a subdirectory. Each entry contains the name of the file and the file's index node reference number (i-node number). The i-node number points to the unique index node assigned to the file. The i-node number describes the location of the data associated with the file. Directories are created and controlled by a separate set of commands.
Special files
Special files define devices for the system or are temporary files created by processes. The basic types of special files are FIFO (first-in, first-out), block, and character. FIFO files are also called pipes. Pipes are created by one process to temporarily allow communication with another process. These files cease to exist when the first process finishes. Block and character files define devices.
Every file has a set of permissions (called access modes) that determine who can read, modify, or execute the file.
Related concepts
File and directory access modes Every file has an owner. For new files, the user who creates the file is the owner of that file. The owner assigns an access mode to the file. Access modes grant other system users permission to read, modify, or execute the file. Only the file's owner or users with root authority can change the access mode of a file.
File naming conventions
The name of each file must be unique within the directory where it is stored. This ensures that the file also has a unique path name in the file system.
File naming guidelines are:
A file name can be up to 255 characters long and can contain letters, numbers, and underscores.
The operating system is case-sensitive, which means it distinguishes between uppercase and lowercase letters in file names. Therefore,
FILEA,FiLea, andfileaare three distinct file names, even if they reside in the same directory.File names should be as descriptive and meaningful as possible.
Directories follow the same naming conventions as files.
Certain characters have special meaning to the operating system. Avoid using these characters when you are naming files. These characters include the following:
/ \ " ’ * ; - ? [ ] ( ) ~ ! $ { } < > # @ & | space tab newline
- A file name is hidden from a normal directory listing if it begins with a dot (
.). When the ls command is entered with the-aflag, the hidden files are listed along with regular files and directories.
File path names
The path name for each file and directory in the file system consists of the names of every directory that precedes it in the tree structure.
Because all paths in a file system originate from the /(root) directory, each file in the file system has a unique relationship to the root directory, known as the absolute path name. Absolute path names begin with the slash (/) symbol. For example, the absolute path name of file h could be /B/C/h. Notice that two files named h can exist in the system. Because the absolute paths to the two files are different, /B/h and
/B/C/h, each file named h has a unique name within the system. Every component of a path name is a directory except the final component. The final component of a path name can be a file name.
Note: Path names cannot exceed 1023 characters in length.
Pattern matching with wildcards and metacharacters
Wildcard characters provide a convenient way to specify multiple file names or directory names.
The wildcard characters are asterisk (*) and question mark (?). The metacharacters are open and close square brackets ([ ]), hyphen (-), and exclamation mark (!).
Pattern matching using the * wildcard character:
Use the asterisk (*) to match any sequence or string of characters.
The (*) indicates any characters, including no characters.
See the following examples:
- If you have the following files in your directory:
1test 2test afile1 afile2 bfile1 file file1 file10 file2 file3
and you want to refer to only the files that begin with file, use:
file*
The files selected would be: file, file1, file10, file2, and file3.
- To refer to only the files that contain the word
file, use:
*file*
The files selected would be: afile1, afile2, bfile1, file, file1, file10, file2, and file3.
Pattern matching using the ? wildcard character:
Use the ? to match any one character.
The ? indicates any single character. See the following examples:
- To refer to only the files that start with file and end with a single character, use:
file?
The files selected would be: file1, file2, file3.
- To refer to only the files that start with file and end with any two characters, use:
file??
The file selected would be: file10.
Pattern matching using [ ] shell metacharacters:
Metacharacters offer another type of wildcard notation by enclosing the desired characters within [ ]. It is like using the ?, but it allows you to choose specific characters to be matched.
The [ ] also allow you to specify a range of values using the hyphen (-). To specify all the letters in the alphabet, use [[:alpha:]]. To specify all the lowercase letters in the alphabet, use [[:lower:]].
See the following examples:
- To refer to only the files that end in
1or2, use:
*file[12]
The files selected would be: afile1, afile2, file1, and file2.
- To refer to only the files that start with any number, use:
[0123456789]* or [0-9]*
The files selected would be: 1test and 2test.
- To refer to only the files that do not begin with an
a, use:
[!a]*
The files selected would be: 1test, 2test, bfile1, file, file1, file10, file2, and file3.
Pattern matching versus regular expressions
Regular expressions allow you to select specific strings from a set of character strings. The use of regular expressions is generally associated with text processing.
Regular expressions can represent a wide variety of possible strings. While many regular expressions can be interpreted differently depending on the current locale, internationalization features provide for contextual invariance across locales.
See the examples in the following comparison:
Pattern Matching Regular Expression
* .*
? .
[!a] [^a]
[abc] [abc]
[[:alpha:]] [[:alpha:]]
See the awk command in the Commands Reference, Volume 1 for the complete syntax.
파일 관리
시스템의 파일을 다루는 방법은 여러 가지입니다. 보통 텍스트 편집기로 텍스트 파일을 만듭니다.
UNIX 환경의 흔한 편집기는 vi와 ed입니다. 여러 텍스트 편집기가 있으므로 편한 것을 고를 수 있습니다.
입출력 방향 바꾸기로도 파일을 만들 수 있습니다. 명령의 출력을 새 파일로 보내거나 기존 파일에 덧붙일 수 있습니다.
파일을 만들고 고친 뒤에는 파일을 다른 디렉터리로 복사하거나 옮기고, 파일 판을 구분하려고 이름을 바꾸거나, 같은 파일에 다른 이름을 붙여야 할 수 있습니다. 여러 프로젝트를 할 때는 디렉터리를 만들어야 할 수도 있습니다.
또 어떤 파일은 지워야 할 수 있습니다. 디렉터리는 오래되거나 쓸모없는 정보가 든 파일로 금세 어지러워집니다. 시스템의 저장 공간을 확보하려면 더 이상 필요 없는 파일을 꼭 지웁니다.
관련 개념
- 입출력 방향 바꾸기 — AIX 운영 체제에서는 특정 입출력 명령과 기호로 시스템에 드나드는 데이터의 입력과 출력(I/O)을 다룰 수 있습니다.
파일 지우기(rm 명령)
rm 명령으로 더 이상 필요 없는 파일을 지웁니다.
rm 명령은 지정한 파일, 파일 그룹, 디렉터리 안 목록에서 고른 파일의 항목을 지웁니다. rm 명령으로 파일을 지울 때는 사용자 확인, 파일 읽기 권한, 쓰기 권한이 필요 없습니다. 그러나 파일이 든 디렉터리에 쓰기 권한이 있어야 합니다.
rm 명령 쓰는 예는 다음과 같습니다.
myfile이라는 파일을 지우려면 다음을 입력합니다.
rm myfile
mydir디렉터리의 모든 파일을 하나씩 지우려면 다음을 입력합니다.
rm -i mydir/*
파일 이름이 나올 때마다 y를 입력하고 Enter를 누르면 파일을 지웁니다. 파일을 남기려면 Enter만 누릅니다.
전체 구문은 Commands Reference, Volume 4의 rm 명령을 봅니다.
파일 옮기기와 이름 바꾸기(mv 명령)
mv 명령으로 파일과 디렉터리를 다른 디렉터리로 옮기거나 파일·디렉터리 이름을 바꿉니다. 새 이름을 지정하지 않고 파일이나 디렉터리를 새 디렉터리로 옮기면 원래 이름을 유지합니다.
주의: -i 플래그를 지정하지 않으면 mv 명령은 기존 파일을 여럿 덮어쓸 수 있습니다. -i 플래그는 파일을 덮어쓰기 전에 확인을 묻습니다. -f 플래그는 묻지 않습니다. -f와 -i 플래그를 함께 지정하면 나중에 지정한 플래그가 우선합니다.
mv 명령으로 파일 옮기기
mv 명령 쓰는 예는 다음과 같습니다.
- 파일을 다른 디렉터리로 옮기며 새 이름을 붙이려면 다음을 입력합니다.
mv intro manual/chap1
이렇게 하면 intro 파일이 manual/chap1로 옮겨집니다(원문은 디렉터리라고 적음). intro라는 이름은 현재 디렉터리에서 지워지고, 같은 파일이 manual 디렉터리에 chap1로 나타납니다.
- 이름을 유지한 채 파일을 다른 디렉터리로 옮기려면 다음을 입력합니다.
mv chap3 manual
이렇게 하면 chap3이 manual/chap3으로 옮겨집니다.
mv 명령으로 파일 이름 바꾸기
mv 명령으로 파일을 다른 디렉터리로 옮기지 않고 이름만 바꿉니다.
파일 이름을 바꾸려면 다음을 입력합니다.
mv appendix apndx.a
이렇게 하면 appendix 파일의 이름이 apndx.a로 바뀝니다. apndx.a라는 파일이 이미 있으면 그 예전 내용은 appendix 파일의 내용으로 바뀝니다.
전체 구문은 Commands Reference, Volume 3의 mv 명령을 봅니다.
파일 복사(cp 명령)
cp 명령으로 SourceFile이나 SourceDirectory 매개변수로 지정한 파일·디렉터리 내용을 TargetFile이나 TargetDirectory 매개변수로 지정한 파일·디렉터리로 복사합니다.
TargetFile로 지정한 파일이 있으면 복사본이 경고 없이 원래 내용을 덮어씁니다. SourceFile을 여러 개 복사하면 대상은 디렉터리여야 합니다.
새 대상에 같은 이름의 파일이 있으면 복사한 파일이 그 파일을 덮어씁니다. 그래서 대상 디렉터리에 같은 이름의 파일이 없도록 복사본에 새 이름을 붙이는 것이 좋습니다.
SourceFile의 사본을 디렉터리에 넣으려면 TargetDirectory 매개변수에 기존 디렉터리 경로를 지정합니다. 경로 끝에 새 파일 이름을 지정하지 않으면 디렉터리로 복사한 파일은 각자 이름을 유지합니다. -r이나 -R 플래그를 지정하면 cp 명령은 디렉터리 전체를 다른 디렉터리로 복사합니다.
-R 플래그로 특수 장치 파일도 복사할 수 있습니다. -R을 지정하면 특수 파일이 새 경로 이름 아래 다시 만들어집니다. -r 플래그를 지정하면 cp 명령은 특수 파일을 정규 파일로 복사하려고 합니다.
cp 명령 쓰는 예는 다음과 같습니다.
- 현재 디렉터리에 파일 사본을 만들려면 다음을 입력합니다.
cp prog.c prog.bak
이렇게 하면 prog.c가 prog.bak으로 복사됩니다. prog.bak 파일이 없으면 cp 명령이 만듭니다. 있으면 cp 명령이 prog.c 파일의 사본으로 바꿉니다.
- 현재 디렉터리의 파일을 다른 디렉터리로 복사하려면 다음을 입력합니다.
cp jones /home/nick/clients
이렇게 하면 jones 파일이 /home/nick/clients/jones로 복사됩니다.
- 한 디렉터리의 모든 파일을 새 디렉터리로 복사하려면 다음을 입력합니다.
cp /home/janet/clients/* /home/nick/customers
이렇게 하면 clients 디렉터리의 파일만 customers 디렉터리로 복사됩니다.
- 특정 파일 묶음을 다른 디렉터리로 복사하려면 다음을 입력합니다.
cp jones lewis smith /home/nick/clients
이렇게 하면 현재 작업 디렉터리의 jones, lewis, smith 파일이 /home/nick/clients 디렉터리로 복사됩니다.
- 패턴 일치 문자로 파일을 복사하려면 다음을 입력합니다.
cp programs/*.c .
이렇게 하면 programs 디렉터리에서 .c로 끝나는 파일이 점 하나(.)로 나타낸 현재 디렉터리로 복사됩니다. c와 마지막 점 사이에 공백을 꼭 넣어야 합니다.
전체 구문은 Commands Reference, Volume 1의 cp 명령을 봅니다.
파일 찾기(find 명령)
find 명령으로 지정한 Path마다 디렉터리 트리를 재귀적으로 훑어, 아래 설명하는 항으로 쓴 부울 식과 맞는 파일을 찾습니다.
find 명령의 출력은 Expression 매개변수에 지정한 항에 따라 달라집니다.
find 명령 쓰는 예는 다음과 같습니다.
- 파일 시스템에서 이름이
.profile인 모든 파일을 나열하려면 다음을 입력합니다.
find / -name .profile
파일 시스템 전체를 찾아 .profile이라는 모든 파일의 전체 경로 이름을 씁니다. 슬래시(/)는 find 명령에 /(root) 디렉터리와 그 모든 하위 디렉터리를 찾으라고 알립니다. 시간을 아끼려면 파일이 있을 만한 디렉터리를 지정해 찾는 범위를 좁힙니다.
- 현재 디렉터리 트리에서 권한 코드가 정확히
0600인 파일을 나열하려면 다음을 입력합니다.
find . -perm 0600
소유자 읽기와 소유자 쓰기 권한만 있는 파일의 이름을 나열합니다. 점(.)은 find 명령에 현재 디렉터리와 그 하위 디렉터리를 찾으라고 알립니다. 권한 코드 설명은 chmod 명령을 봅니다.
- 여러 디렉터리에서 특정 권한 코드를 가진 파일을 찾으려면 다음을 입력합니다.
find manual clients proposals -perm -0600
소유자 읽기와 소유자 쓰기 권한이 있고 다른 권한도 있을 수 있는 파일의 이름을 나열합니다. manual, clients, proposals 디렉터리와 그 하위 디렉터리를 찾습니다. 앞 예에서 -perm 0600은 권한 코드가 정확히 0600인 파일만 고릅니다. 이 예에서 -perm -0600은 0600이 나타내는 접근과 그 위의 다른 접근도 허용하는 권한 코드의 파일을 고릅니다. 권한 코드 0622와 2744도 일치합니다.
- 현재 디렉터리에서 지난 24시간 안에 바뀐 모든 파일을 나열하려면 다음을 입력합니다.
find . -ctime 1
- 링크가 여러 개인 정규 파일을 찾으려면 다음을 입력합니다.
find . -type f -links +1
링크가 둘 이상(-links +1)인 일반 파일(-type f)의 이름을 나열합니다.
참고: 모든 디렉터리에는 링크가 적어도 둘 있습니다. 부모 디렉터리의 항목과 자기 .(점) 항목입니다. 다중 파일 링크에 관한 자세한 내용은 ln 명령을 봅니다.
- 크기가 정확히 414바이트인 모든 파일을 찾으려면 다음을 입력합니다.
find . -size 414c
전체 구문은 Commands Reference, Volume 2의 find 명령을 봅니다.
파일 종류 보기(file 명령)
file 명령은 File이나 -f FileList 매개변수로 지정한 파일을 읽고, 각 파일에 여러 시험을 해서 종류별로 분류하려고 합니다. 그런 다음 파일 종류를 표준 출력에 씁니다.
파일이 ASCII로 보이면 file 명령은 처음 512바이트를 살펴 언어를 판단합니다. ASCII로 보이지 않으면 바이너리 데이터 파일인지, 확장 문자가 든 텍스트 파일인지 더 판단하려고 합니다.
File 매개변수가 실행 파일이나 객체 모듈 파일을 지정하고 버전 번호가 0보다 크면 file 명령은 버전 스탬프를 보여 줍니다.
file 명령은 /etc/magic 파일로 매직 넘버가 있는 파일, 곧 종류를 나타내는 숫자나 문자열 상수가 든 파일을 식별합니다.
file 명령 쓰는 예는 다음과 같습니다.
myfile이라는 파일에 든 정보의 종류를 보려면 다음을 입력합니다.
file myfile
myfile의 파일 종류(directory, data, ASCII text, C program source, archive 등)를 보여 줍니다.
- 파일 이름 목록이 든
filenames.lst파일에 적힌 각 파일의 종류를 보려면 다음을 입력합니다.
file -f filenames.lst
filenames.lst 파일에 적힌 각 파일의 종류를 보여 줍니다. 파일 이름은 한 줄에 하나씩 있어야 합니다.
- 현재 디렉터리의 모든 파일 이름이 든
filenames.lst파일을 만들려면 다음을 입력합니다.
ls > filenames.lst
filenames.lst 파일을 원하는 대로 편집합니다.
전체 구문은 Commands Reference, Volume 2의 file 명령을 봅니다.
파일 내용을 보여 주는 명령(pg, more, page, cat 명령)
pg, more, page 명령으로 파일 내용을 보고 파일이 표시되는 속도를 제어할 수 있습니다.
cat 명령으로도 파일 하나 이상의 내용을 화면에 보여 줄 수 있습니다. cat 명령을 pg 명령과 함께 쓰면 파일 내용을 한 화면씩 읽을 수 있습니다.
입출력 방향 바꾸기로도 파일 내용을 볼 수 있습니다.
관련 개념
- 입출력 방향 바꾸기
pg 명령 쓰기
pg 명령은 File 매개변수에 지정한 파일을 읽어 한 화면씩 표준 출력에 씁니다.
File 매개변수로 하이픈(-)을 지정하거나 옵션 없이 pg 명령을 실행하면 pg 명령은 표준 입력을 읽습니다. 화면마다 뒤에 프롬프트가 나옵니다. Enter 키를 누르면 다음 화면이 나옵니다. pg 명령의 하위 명령으로 이미 지나간 내용을 다시 볼 수 있습니다.
예를 들어 myfile 파일 내용을 한 페이지씩 보려면 다음을 입력합니다.
pg myfile
전체 구문은 Commands Reference, Volume 4의 pg 명령을 봅니다.
more나 page 명령 쓰기
more나 page 명령으로 이어지는 텍스트를 한 화면씩 봅니다.
화면마다 멈추고 화면 아래에 파일 이름과 진행 백분율(예: myfile (7%))을 보여 줍니다. 그때 Enter 키를 누르면 more 명령이 한 줄을 더 보여 줍니다. 스페이스바를 누르면 텍스트 한 화면을 더 보여 줍니다.
참고: 어떤 터미널 모델에서는 more 명령이 다음 화면을 보여 주기 전에 스크롤하는 대신 화면을 지웁니다.
예를 들어 myfile이라는 파일을 보려면 다음을 입력합니다.
more myfile
다음 화면을 보려면 스페이스바를 누릅니다.
전체 구문은 Commands Reference, Volume 3의 more 명령을 봅니다.
cat 명령
cat 명령은 각 File 매개변수를 차례로 읽어 표준 출력에 씁니다.
다음 예를 봅니다.
notes파일의 내용을 보려면 다음을 입력합니다.
cat notes
파일이 24줄보다 길면 일부가 화면 밖으로 밀려납니다. 파일을 한 페이지씩 보려면 pg 명령을 씁니다.
notes,notes2,notes3파일의 내용을 보려면 다음을 입력합니다.
cat notes notes2 notes3
전체 구문은 Commands Reference, Volume 1의 cat 명령을 봅니다.
파일 안에서 텍스트 문자열 찾기(grep 명령)
grep 명령은 지정한 파일에서 Pattern 매개변수로 지정한 패턴을 찾아 일치하는 줄을 모두 표준 출력에 씁니다.
grep 명령 쓰는 예는 다음과 같습니다.
pgm.s라는 파일에서 패턴 일치 문자*,^,?,[,],\(,\),\{,\}가운데 일부가 든 패턴, 이 경우 대문자나 소문자로 시작하는 줄을 찾으려면 다음을 입력합니다.
grep "^[a-zA-Z]" pgm.s
pgm.s 파일에서 문자로 시작하는 모든 줄을 보여 줍니다.
sort.c라는 파일에서 특정 패턴과 맞지 않는 모든 줄을 보려면 다음을 입력합니다.
grep -v bubble sort.c
sort.c 파일에서 bubble이라는 단어가 없는 모든 줄을 보여 줍니다.
- ls 명령 출력에서 문자열
staff와 맞는 줄을 보려면 다음을 입력합니다.
ls -l | grep staff
전체 구문은 Commands Reference, Volume 2의 grep 명령을 봅니다.
텍스트 파일 정렬(sort 명령)
sort 명령은 File 매개변수로 지정한 파일의 줄을 알파벳순으로 정렬해 결과를 표준 출력에 씁니다.
File 매개변수에 파일을 여러 개 지정하면 sort 명령은 파일을 이어 붙여 한 파일처럼 정렬합니다.
참고: sort 명령은 대소문자를 가리며 대문자를 소문자 앞에 둡니다(이 동작은 로케일에 따라 다릅니다).
다음 예에서 names 파일의 내용은 다음과 같고
marta
denise
joyce
endrica
melanie
states 파일의 내용은 다음과 같습니다.
texas
colorado
ohio
names파일의 정렬된 내용을 보려면 다음을 입력합니다.
sort names
시스템은 다음과 비슷한 정보를 보여 줍니다.
denise
endrica
joyce
marta
melanie
names와states파일의 정렬된 내용을 보려면 다음을 입력합니다.
sort names states
시스템은 다음과 비슷한 정보를 보여 줍니다.
colorado
denise
endrica
joyce
marta
melanie
ohio
texas
names파일의 원래 내용을 정렬한 내용으로 바꾸려면 다음을 입력합니다.
sort -o names names
names 파일의 내용이 같은 데이터를 정렬한 순서로 바뀝니다.
전체 구문은 Commands Reference, Volume 5의 sort 명령을 봅니다.
파일 비교(diff 명령)
diff 명령으로 텍스트 파일을 비교합니다. 파일 하나씩이나 디렉터리 내용을 비교할 수 있습니다.
diff 명령을 정규 파일에 실행하거나 다른 디렉터리의 텍스트 파일을 비교하면, 두 파일이 같아지려면 어느 줄을 바꿔야 하는지 알려 줍니다.
diff 명령 쓰는 예는 다음과 같습니다.
- 두 파일을 비교하려면 다음을 입력합니다.
diff chap1.bak chap1
chap1.bak과 chap1 파일의 차이를 보여 줍니다.
- 공백 양의 차이는 무시하고 두 파일을 비교하려면 다음을 입력합니다.
diff -w prog.c.bak prog.c
두 파일이 단어 사이의 공백과 탭 수만 다르면 diff -w 명령은 두 파일을 같다고 봅니다.
전체 구문은 Commands Reference, Volume 2의 diff 명령을 봅니다.
파일의 단어, 줄, 바이트 세기(wc 명령)
wc 명령으로 File 매개변수에 지정한 파일의 줄, 단어, 바이트 수를 셉니다.
File 매개변수에 파일을 지정하지 않으면 표준 입력을 씁니다. 결과를 표준 출력에 쓰고 지정한 모든 파일의 합계를 유지합니다. 플래그를 지정하면 플래그 순서가 출력 순서를 정합니다. 단어는 공백, 탭, 줄 바꿈 문자로 구분한 문자열입니다.
명령행에 파일을 지정하면 수와 함께 파일 이름도 출력됩니다.
다음 예를 봅니다.
chap1파일의 줄, 단어, 바이트 수를 보려면 다음을 입력합니다.
wc chap1
chap1 파일의 줄, 단어, 바이트 수를 보여 줍니다.
- 바이트와 단어 수만 보려면 다음을 입력합니다.
wc -cw chap*
이름이 chap으로 시작하는 각 파일의 바이트와 단어 수, 그리고 합계를 보여 줍니다.
전체 구문은 Commands Reference, Volume 6의 wc 명령을 봅니다.
파일의 첫 줄들 보기(head 명령)
head 명령으로 지정한 각 파일이나 표준 입력의 처음 몇 줄을 표준 출력에 씁니다.
head 명령에 플래그를 지정하지 않으면 기본으로 처음 10줄을 보여 줍니다.
예를 들어 Test 파일의 처음 다섯 줄을 보려면 다음을 입력합니다.
head -5 Test
전체 구문은 Commands Reference, Volume 2의 head 명령을 봅니다.
파일의 마지막 줄들 보기(tail 명령)
tail 명령으로 File 매개변수에 지정한 파일을 지정한 지점부터 표준 출력에 씁니다.
다음 예를 봅니다.
notes파일의 마지막 10줄을 보려면 다음을 입력합니다.
tail notes
notes파일 끝에서부터 읽기 시작할 줄 수를 지정하려면 다음을 입력합니다.
tail -20 notes
- 200번째 바이트부터
notes파일을 한 페이지씩 보려면 다음을 입력합니다.
tail -c +200 notes | pg
accounts라는 파일이 커지는 것을 따라가려면 다음을 입력합니다.
tail -f accounts
accounts 파일의 마지막 10줄을 보여 줍니다. tail 명령은 accounts 파일에 줄이 더해질 때마다 계속 보여 줍니다. Ctrl-C 키를 눌러 멈출 때까지 표시가 계속됩니다.
전체 구문은 Commands Reference, Volume 5의 tail 명령을 봅니다.
텍스트 파일 구역 잘라내기(cut 명령)
cut 명령으로 파일 각 줄에서 고른 바이트, 문자, 필드를 표준 출력에 씁니다.
다음 예를 봅니다.
- 파일 각 줄의 몇몇 필드를 보려면 다음을 입력합니다.
cut -f1,5 -d: /etc/passwd
시스템 암호 파일의 로그인 이름과 사용자 전체 이름 필드를 보여 줍니다. 콜론으로 구분한(-d:) 첫째와 다섯째 필드(-f1,5)입니다.
/etc/passwd파일이 다음과 같으면
su:*:0:0:User with special privileges:/:/usr/bin/sh
daemon:*:1:1::/etc:
bin:*:2:2::/usr/bin:
sys:*:3:3::/usr/src:
adm:*:4:4:system administrator:/var/adm:/usr/bin/sh
pierre:*:200:200:Pierre Harper:/home/pierre:/usr/bin/sh
joan:*:202:200:Joan Brown:/home/joan:/usr/bin/sh
cut 명령은 다음을 만듭니다.
su:User with special privileges
daemon:
bin:
sys:
adm:system administrator
pierre:Pierre Harper
joan:Joan Brown
전체 구문은 Commands Reference, Volume 1의 cut 명령을 봅니다.
텍스트 파일 구역 붙이기(paste 명령)
paste 명령으로 최대 12개 파일의 줄을 한 파일로 합칩니다.
다음 예를 봅니다.
- 다음 텍스트가 든
names라는 파일이 있고
rachel
jerry
mark
linda
scott
다음 텍스트가 든 places라는 파일과
New York
Austin
Chicago
Boca Raton
Seattle
다음 텍스트가 든 dates라는 파일이 있을 때
February 5
March 13
June 21
July 16
November 4
names, places, dates 파일의 텍스트를 붙이려면 다음을 입력합니다.
paste names places dates > npd
names 파일의 데이터는 한 열에, places 파일은 다른 열에, dates 파일은 셋째 열에 든 npd라는 파일을 만듭니다. 이제 npd 파일에는 다음이 들어 있습니다.
rachel New York February 5
jerry Austin March 13
mark Chicago June 21
linda Boca Raton July 16
scott Seattle November 4
각 줄에서 이름, 장소, 날짜는 탭 문자로 구분됩니다. 탭 정지가 8열마다 있으므로 열이 맞지 않습니다.
- 탭이 아닌 문자로 열을 구분하려면 다음을 입력합니다.
paste -d"!@" names places dates > npd
!와 @를 번갈아 열 구분자로 씁니다. names, places, dates 파일이 예 1과 같으면 npd 파일에는 다음이 들어 있습니다.
rachel!New York@February 5
jerry!Austin@March 13
mark!Chicago@June 21
linda!Boca Raton@July 16
scott!Seattle@November 4
- 현재 디렉터리를 네 열로 나열하려면 다음을 입력합니다.
ls | paste - - - -
하이픈(-)마다 paste 명령에 표준 입력에서 읽은 데이터로 열 하나를 만들라고 알립니다. 첫 줄은 첫째 열에, 둘째 줄은 둘째 열에 들어가는 식입니다.
전체 구문은 Commands Reference, Volume 4의 paste 명령을 봅니다.
텍스트 파일 줄 번호 매기기(nl 명령)
nl 명령은 지정한 파일(기본은 표준 입력)을 읽어 입력 줄에 번호를 매기고, 번호 매긴 줄을 표준 출력에 씁니다.
다음 예를 봅니다.
- 비어 있지 않은 줄에만 번호를 매기려면 다음을 입력합니다.
nl chap1
본문 구역에서 비어 있지 않은 줄에만 번호를 매긴 chap1 목록을 보여 줍니다.
- 모든 줄에 번호를 매기려면 다음을 입력합니다.
nl -ba chap1
chap1이라는 파일의 빈 줄을 포함한 모든 줄에 번호를 매깁니다.
전체 구문은 Commands Reference, Volume 4의 nl 명령을 봅니다.
텍스트 파일의 열 지우기(colrm 명령)
colrm 명령으로 파일에서 지정한 열을 지웁니다. 입력은 표준 입력에서 받고 출력은 표준 출력으로 보냅니다.
매개변수 하나로 호출하면 각 줄에서 지정한 열부터 마지막 열까지 지웁니다. 매개변수 두 개로 호출하면 첫째로 지정한 열부터 둘째로 지정한 열까지 지웁니다.
참고: 열 번호는 1부터 시작합니다.
다음 예를 봅니다.
text.fil파일에서 열을 지우려면 다음을 입력합니다.
colrm 6 < text.fil
text.fil에 다음이 들어 있으면
123456789
colrm 명령은 다음을 보여 줍니다.
12345
전체 구문은 Commands Reference, Volume 1의 colrm 명령을 봅니다.
영어 원문
Administering files
There are many ways to work with the files on your system. Usually you create a text file with a text editor.
The common editors in the UNIX environment are vi and ed. Because several text editors are available, you can choose an editor you feel comfortable with.
You can also create files by using input and output redirection. You can send the output of a command to a new file or append it to an existing file.
After creating and modifying files, you might have to copy or move files from one directory to another, rename files to distinguish different versions of a file, or give different names to the same file. You might also need to create directories when working on different projects.
Also, you might need to delete certain files. Your directory can quickly get cluttered with files that contain old or useless information. To release storage space on your system, ensure that you delete files that are no longer needed.
Related concepts
Input and output redirection The AIX operating system allows you to manipulate the input and output (I/O) of data to and from your system by using specific I/O commands and symbols.
Deleting files (rm command)
Use the rm command to remove files you no longer need.
The rm command removes the entries for a specified file, group of files, or certain select files from a list within a directory. User confirmation, read permission, and write permission are not required before a file is removed when you use the rm command. However, you must have write permission for the directory containing the file.
The following are examples of how to use the rm command:
- To delete the file named
myfile, type the following:
rm myfile
- To delete all the files in the
mydirdirectory, one by one, type the following:
rm -i mydir/*
After each file name displays, type y and press Enter to delete the file. Or to keep the file, just press Enter.
See the rm command in the Commands Reference, Volume 4 for the complete syntax.
Moving and renaming files (mv command)
Use the mv command to move files and directories from one directory to another or to rename a file or directory. If you move a file or directory to a new directory without specifying a new name, it retains its original name.
Attention: The mv command can overwrite many existing files unless you specify the -i flag. The -i flag prompts you to confirm before it overwrites a file. The -f flag does not prompt you. If both the -f and -i flags are specified in combination, the last flag specified takes precedence.
Moving files with mv command
The following are examples of how to use the mv command:
- To move a file to another directory and give it a new name, type the following:
mv intro manual/chap1
This moves the intro file to the manual/chap1 directory. The name intro is removed from the current directory, and the same file appears as chap1 in the manual directory.
- To move a file to another directory, keeping the same name, type the following:
mv chap3 manual
This moves chap3 to manual/chap3.
Renaming files with mv command
Use the mv command to change the name of a file without moving it to another directory.
To rename a file, type the following:
mv appendix apndx.a
This renames the appendix file to apndx.a. If a file named apndx.a already exists, its old contents are replaced with those of the appendix file.
See the mv command in the Commands Reference, Volume 3 for the complete syntax.
Copying files (cp command)
Use the cp command to create a copy of the contents of the file or directory specified by the SourceFile or SourceDirectory parameters into the file or directory specified by the TargetFile or TargetDirectory parameters.
If the file specified as the TargetFile exists, the copy writes over the original contents of the file without warning. If you are copying more than one SourceFile, the target must be a directory.
If a file with the same name exists at the new destination, the copied file overwrites the file at the new destination. Therefore, it is a good practice to assign a new name for the copy of the file to ensure that a file of the same name does not exist in the destination directory.
To place a copy of the SourceFile into a directory, specify a path to an existing directory for the TargetDirectory parameter. Files maintain their respective names when copied to a directory unless you specify a new file name at the end of the path. The cp command also copies entire directories into other directories if you specify the -r or -R flags.
You can also copy special-device files using the -R flag. Specifying -R causes the special files to be re-created under the new path name. Specifying the -r flag causes the cp command to attempt to copy the special files to regular files.
The following are examples of how to use the cp command:
- To make a copy of a file in the current directory, type the following:
cp prog.c prog.bak
This copies prog.c to prog.bak. If the prog.bak file does not already exist, then the cp command creates it. If it does exist, then the cp command replaces it with a copy of the prog.c file.
- To copy a file in your current directory into another directory, type the following:
cp jones /home/nick/clients
This copies the jones file to /home/nick/clients/jones.
- To copy all the files in a directory to a new directory, type the following:
cp /home/janet/clients/* /home/nick/customers
This copies only the files in the clients directory to the customers directory.
- To copy a specific set of files to another directory, type the following:
cp jones lewis smith /home/nick/clients
This copies the jones, lewis, and smith files in your current working directory to the /home/nick/clients directory.
- To use pattern-matching characters to copy files, type the following:
cp programs/*.c .
This copies the files in the programs directory that end with .c to the current directory, indicated by the single dot (.). You must type a space between the c and the final dot.
See the cp command in the Commands Reference, Volume 1 for the complete syntax.
Finding files (find command)
Use the find command to recursively search the directory tree for each specified Path, seeking files that match a Boolean expression written using the terms given in the following text.
The output from the find command depends on the terms specified by the Expression parameter.
The following are examples of how to use the find command:
- To list all files in the file system with the name
.profile, type the following:
find / -name .profile
This searches the entire file system and writes the complete path names of all files named .profile. The slash (/) tells the find command to search the /(root) directory and all of its subdirectories. To save time, limit the search by specifying the directories where you think the files might be.
- To list files having a specific permission code of
0600in the current directory tree, type the following:
find . -perm 0600
This lists the names of the files that have only owner-read and owner-write permission. The dot (.) tells the find command to search the current directory and its subdirectories. For an explanation of permission codes, see the chmod command.
- To search several directories for files with certain permission codes, type the following:
find manual clients proposals -perm -0600
This lists the names of the files that have owner-read and owner-write permission and possibly other permissions. The manual, clients, and proposals directories and their subdirectories are searched. In the previous example, -perm 0600 selects only files with permission codes that match 0600 exactly. In this example, -perm -0600 selects files with permission codes that allow the accesses indicated by 0600 and other accesses above the 0600 level. This also matches the permission codes 0622 and 2744.
- To list all files in the current directory that have been changed during the current 24-hour period, type the following:
find . -ctime 1
- To search for regular files with multiple links, type the following:
find . -type f -links +1
This lists the names of the ordinary files (-type f) that have more than one link (-links +1).
Note: Every directory has at least two links: the entry in its parent directory and its own .(dot) entry. For more information on multiple file links, see the ln command.
- To search for all files that are exactly 414 bytes in length, type the following:
find . -size 414c
See the find command in the Commands Reference, Volume 2 for the complete syntax.
Displaying the file type (file command)
Use the file command to read the files specified by the File or -fFileList parameter, perform a series of tests on each one, and attempt to classify the files by type. The command then writes the file types to standard output.
If a file appears to be ASCII, the file command examines the first 512 bytes and determines its language. If a file does not appear to be ASCII, the file command further attempts to determine whether it is a binary data file or a text file that contains extended characters.
If the File parameter specifies an executable or object module file and the version number is greater than 0, the file command displays the version stamp.
The file command uses the /etc/magic file to identify files that have a magic number; that is, any file containing a numeric or string constant that indicates the type.
The following are examples of how to use the file command:
- To display the type of information the file named
myfilecontains, type the following:
file myfile
This displays the file type of myfile (such as directory, data, ASCII text, C program source, or archive).
- To display the type of each file named in the
filenames.lstfile, which contains a list of file names, type the following:
file -f filenames.lst
This displays the type of each file named in the filenames.lst file. Each file name must display on a separate line.
- To create the
filenames.lstfile that contains all the file names in the current directory, type the following:
ls > filenames.lst
Edit the filenames.lst file as desired.
See the file command in the Commands Reference, Volume 2 for the complete syntax.
Commands for displaying file contents (pg, more, page, and cat commands):
The pg, more, and page commands allow you to view the contents of a file and control the speed at which your files are displayed.
You can also use the cat command to display the contents of one or more files on your screen. Combining the cat command with the pg command allows you to read the contents of a file one full screen at a time.
You can also display the contents of files by using input and output redirection.
Related concepts
Input and output redirection The AIX operating system allows you to manipulate the input and output (I/O) of data to and from your system by using specific I/O commands and symbols.
Using the pg command:
Use the pg command to read the files named in the File parameter and writes them to standard output one screen at a time.
If you specify hyphen (-) as the File parameter or run the pg command without options, the pg command reads standard input. Each screen is followed by a prompt. If you press the Enter key, another screen displays. Subcommands used with the pg command let you review content that has already passed.
For example, to look at the contents of the file myfile one page at a time, type the following:
pg myfile
See the pg command in the Commands Reference, Volume 4 for the complete syntax.
Using the more or page commands:
Use the more or page command to display continuous text one screen at a time.
It pauses after each screen and prints the filename and percent completed (for example, myfile (7%)) at the bottom of the screen. If you then press the Enter key, the more command displays an additional line. If you press the Spacebar, the more command displays another screen of text.
Note: On some terminal models, the more command clears the screen, instead of scrolling, before displaying the next screen of text.
For example, to view a file named myfile, type the following:
more myfile
Press the Spacebar to view the next screen.
See the more command in theCommands Reference, Volume 3 for the complete syntax.
cat command:
Use the cat command to read each File parameter in sequence and writes it to standard output.
See the following examples:
- To display the contents of the file
notes, type the following:
cat notes
If the file is more than 24 lines long, some of it scrolls off the screen. To list a file one page at a time, use the pg command.
- To display the contents of the files
notes,notes2, andnotes3, type the following:
cat notes notes2 notes3
See the cat command in the Commands Reference, Volume 1 for the complete syntax.
Finding text strings within files (grep command)
Use the grep command to search the specified file for the pattern specified by the Pattern parameter and writes each matching line to standard output.
The following are examples of how to use the grep command:
- To search in a file named
pgm.sfor a pattern that contains some of the pattern-matching characters*, ^, ?, [, ],\(,\),\{, and\}, in this case, lines starting with any lowercase or uppercase letter, type the following:
grep "^[a-zA-Z]" pgm.s
This displays all lines in the pgm.s file that begin with a letter.
- To display all lines in a file named
sort.cthat do not match a particular pattern, type the following:
grep -v bubble sort.c
This displays all lines that do not contain the word bubble in the sort.c file.
- To display lines in the output of the ls command that match the string
staff, type the following:
ls -l | grep staff
See the grep command in the Commands Reference, Volume 2 for the complete syntax.
Sorting text files (sort command)
Use the sort command to alphabetize lines in the files specified by the File parameters and write the result to standard output.
If the File parameter specifies more than one file, the sort command concatenates the files and alphabetizes them as one file.
Note: The sort command is case-sensitive and orders uppercase letters before lowercase (this behavior is dependent on the locale).
In the following examples, the contents of the file named names are:
marta
denise
joyce
endrica
melanie
and the contents of the file named states are:
texas
colorado
ohio
- To display the sorted contents of the file named
names, type the following:
sort names
The system displays information similar to the following:
denise
endrica
joyce
marta
melanie
- To display the sorted contents of the
namesandstatesfiles, type the following:
sort names states
The system displays information similar to the following:
colorado
denise
endrica
joyce
marta
melanie
ohio
texas
- To replace the original contents of the file named
nameswith its sorted contents, type the following:
sort -o names names
This replaces the contents of the names file with the same data but in sorted order.
See the sort command in the Commands Reference, Volume 5 for the complete syntax.
Comparing files (diff command)
Use the diff command to compare text files. It can compare single files or the contents of directories.
When the diff command is run on regular files, and when it compares text files in different directories, the diff command tells which lines must be changed in the files so that they match.
The following are examples of how to use the diff command:
- To compare two files, type the following:
diff chap1.bak chap1
This displays the differences between the chap1.bak and chap1 files.
- To compare two files while ignoring differences in the amount of white space, type the following:
diff -w prog.c.bak prog.c
If the two files differ only in the number of spaces and tabs between words, the diff -w command considers the files to be the same.
See the diff command in the Commands Reference, Volume 2 for the complete syntax.
Counting words, lines, and bytes in files (wc command)
Use the wc command to count the number of lines, words, and bytes in the files specified by the File parameter.
If a file is not specified for the File parameter, standard input is used. The command writes the results to standard output and keeps a total count for all named files. If flags are specified, the ordering of the flags determines the ordering of the output. A word is defined as a string of characters delimited by spaces, tabs, or newline characters.
When files are specified on the command line, their names are printed along with the counts.
See the following examples:
- To display the line, word, and byte counts of the file named
chap1, type the following:
wc chap1
This displays the number of lines, words, and bytes in the chap1 file.
- To display only byte and word counts, type the following:
wc -cw chap*
This displays the number of bytes and words in each file where the name starts with chap, and displays the totals.
See the wc command in the Commands Reference, Volume 6 for the complete syntax.
Displaying the first lines of files (head command)
Use the head command to write to standard output the first few lines of each of the specified files or of the standard input.
If no flag is specified with the head command, the first 10 lines are displayed by default.
For example, to display the first five lines of the Test file, type the following:
head -5 Test
See the head command in the Commands Reference, Volume 2 for the complete syntax.
Displaying the last lines of files (tail command)
Use the tail command to write the file specified by the File parameter to standard output beginning at a specified point.
See the following examples:
- To display the last 10 lines of the
notesfile, type the following:
tail notes
- To specify the number of lines to start reading from the end of the
notesfile, type the following:
tail -20 notes
- To display the
notesfile one page at a time, beginning with the 200th byte, type the following:
tail -c +200 notes | pg
- To follow the growth of the file named
accounts, type the following:
tail -f accounts
This displays the last 10 lines of the accounts file. The tail command continues to display lines as they are added to the accounts file. The display continues until you press the (Ctrl-C) key sequence to stop the display.
See the tail command in the Commands Reference, Volume 5 for the complete syntax.
Cutting sections of text files (cut command)
Use the cut command to write selected bytes, characters, or fields from each line of a file to standard output.
See the following examples:
- To display several fields of each line of a file, type the following:
cut -f1,5 -d: /etc/passwd
This displays the login name and full user name fields of the system password file. These are the first and fifth fields (-f1,5) separated by colons (-d:).
- If the
/etc/passwdfile looks like this:
su:*:0:0:User with special privileges:/:/usr/bin/sh
daemon:*:1:1::/etc:
bin:*:2:2::/usr/bin:
sys:*:3:3::/usr/src:
adm:*:4:4:system administrator:/var/adm:/usr/bin/sh
pierre:*:200:200:Pierre Harper:/home/pierre:/usr/bin/sh
joan:*:202:200:Joan Brown:/home/joan:/usr/bin/sh
the cut command produces:
su:User with special privileges
daemon:
bin:
sys:
adm:system administrator
pierre:Pierre Harper
joan:Joan Brown
See the cut command in the Commands Reference, Volume 1 for the complete syntax.
Pasting sections of text files (paste command)
Use the paste command to merge the lines of up to 12 files into one file.
See the following examples:
- If you have a file named
namesthat contains the following text:
rachel
jerry
mark
linda
scott
and another file named places that contains the following text:
New York
Austin
Chicago
Boca Raton
Seattle
and another file named dates that contains the following text:
February 5
March 13
June 21
July 16
November 4
To paste the text of the files names, places, and dates together, type the following:
paste names places dates > npd
This creates a file named npd that contains the data from the names file in one column, the places file in another, and the dates file in a third. The npd file now contains the following:
rachel New York February 5
jerry Austin March 13
mark Chicago June 21
linda Boca Raton July 16
scott Seattle November 4
A tab character separates the name, place, and date on each line. These columns do not align, because the tab stops are set at every eighth column.
- To separate the columns with a character other than a tab, type the following:
paste -d"!@" names places dates > npd
This alternates ! and @ as the column separators. If the names, places, and dates files are the same as in example 1, then the npd file contains the following:
rachel!New York@February 5
jerry!Austin@March 13
mark!Chicago@June 21
linda!Boca Raton@July 16
scott!Seattle@November 4
- To list the current directory in four columns, type the following:
ls | paste - - - -
Each hyphen (-) tells the paste command to create a column containing data read from the standard input. The first line is put in the first column, the second line in the second column, and so on.
See the paste command in the Commands Reference, Volume 4 for the complete syntax.
Numbering lines in text files (nl command)
Use the nl command to read the specified file (standard input by default), numbers the lines in the input, and writes the numbered lines to standard output.
See the following examples:
- To number only the lines that are not blank, type the following:
nl chap1
This displays a numbered listing of chap1, numbering only the lines that are not blank in the body sections.
- To number all lines, type the following:
nl -ba chap1
This numbers all the lines in the file named chap1, including blank lines.
See the nl command in the Commands Reference, Volume 4 for the complete syntax.
Removing columns in text files (colrm command)
Use the colrm command to remove specified columns from a file. Input is taken from standard input. Output is sent to standard output.
If the command is called with one parameter, the columns of each line from the specified column to the last column are removed. If the command is called with two parameters, the columns from the first specified column to the second specified column are removed.
Note: Column numbering starts with column 1.
See the following examples:
- To remove columns from the
text.filfile, type the following:
colrm 6 < text.fil
If text.fil contains:
123456789
then the colrm command displays:
12345
See the colrm command in the Commands Reference, Volume 1 for the complete syntax.