
예를 들어 다음과 같이 한 파일의 패턴과 일치하는 줄을 다른 파일의 줄에서 순서대로 바꾸고 싶습니다.
파일1.txt:
aaaaaa
bbbbbb
!! 1234
!! 4567
ccccc
ddddd
!! 1111
우리는 !!로 시작하는 줄을 바꾸고 싶습니다. 이 파일의 줄을 사용하여:
파일2.txt:
first line
second line
third line
따라서 결과는 다음과 같아야 합니다.
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
답변1
쉽게 할 수 있습니다앗
awk '
/^!!/{ #for line stared with `!!`
getline <"file2.txt" #read 1 line from outer file into $0
}
1 #alias for `print $0`
' file1.txt
다른 버전
awk '
NR == FNR{ #for lines in first file
S[NR] = $0 #put line in array `S` with row number as index
next #starts script from the beginning
}
/^!!/{ #for line stared with `!!`
$0=S[++count] #replace line by corresponded array element
}
1 #alias for `print $0`
' file2.txt file1.txt
답변2
와 GNU sed
유사awk+getline
$ sed -e '/^!!/{R file2.txt' -e 'd}' file1.txt
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
R
한 번에 한 줄씩 줄 것입니다- 순서가 중요해요, 먼저
R
그 다음d
와 함께perl
$ < file2.txt perl -pe '$_ = <STDIN> if /^!!/' file1.txt
aaaaaa
bbbbbb
first line
second line
ccccc
ddddd
third line
<STDIN>
파일 핸들을 사용하여 읽을 수 있도록 행을 대체하여 파일을 표준 입력으로 전달합니다.- 일치하는 줄이 있으면
$_
표준 입력의 줄로 바꿉니다.