X부터 Y까지의 숫자가 포함된 행을 Z행 다음에 다른 파일에 삽입하는 방법은 무엇입니까?

X부터 Y까지의 숫자가 포함된 행을 Z행 다음에 다른 파일에 삽입하는 방법은 무엇입니까?

저는 두 개의 파일을 만들었습니다.

echo -e "1\n2\n3\n4\n5" > 123.txt
echo -e "a\nb\nc\nd\ne" > abc.txt

123.txt다음을 포함하는 파일을 얻고 싶습니다 .

1
2
3
b
c
d
4
5

즉, abc.txt파일의 세 번째 줄 다음에 파일의 2~4번 줄을 삽입합니다 123.txt.

여기에서 비슷한 질문을 많이 보았지만 적절한 답변을 찾지 못했습니다. 그래도 다음과 같은 줄이 있습니다.

sed -n '2,4p' abc.txt

파일의 세 번째 줄 뒤에 텍스트를 입력하세요.

sed -i '3a\mytext' 123.txt

이전 명령 stdout 또는 /and sed/ 단일 명령을 사용하여 awk이 작업을 어떻게 수행할 수 있습니까?

답변1

시스템에 GNU 버전이 있는 경우 sedGNU 확장 명령을 사용할 수 있습니다 r.

r filename
    As a GNU extension, this command accepts two addresses.

    Queue the contents of filename to be read and inserted into the
    output stream at the end of the current cycle, or when the next input 
    line is read. Note that if filename cannot be read, it is treated as 
    if it were an empty file, without any error indication.

    As a GNU sed extension, the special value /dev/stdin is supported for 
    the file name, which reads the contents of the standard input. 

예를 들어,

$ sed '3r /dev/stdin' 123.txt < <(sed -n '2,4p' abc.txt)
1
2
3
b
c
d
4
5

답변2

awk및를 사용하여 sed:

$ awk 'FNR==3{print;system("sed -n '2,4p' abc.txt");next};1' 123.txt 
1
2
3
b
c
d
4
5

답변3

Pass 를 사용 sed하면 이 r명령을 사용하여 전체 파일을 삽입할 수 있습니다. 파일의 일부를 삽입하려면 해당 부분을 추출하여 에 입력으로 파이프할 수도 있습니다 sed.sed

sed -n '2,4p' abc.txt | sed -i '3r /dev/stdin' 123.txt

를 사용하면 awk하나의 파일을 읽고 중간에 다른 파일로 전환할 수 있습니다.

awk <123.txt >123.txt.new '
    1                                    # print the input line
    NR==3 {                              # after line 3 of 123.txt, …
        while (getline < "abc.txt") {
            ++inner_NR;
            if (inner_NR >= 2) print;    # start printing at line 2 from abc.txt
            if (inner_NR == 4) break;    # stop after line 4
        }
    }
' &&
mv 123.txt.new 123.txt

병합하려는 파일 부분을 추출하는 데 head및 를 사용할 수도 있습니다 .tail

head -n 3 <123.txt >123.txt.new &&
<abc.txt tail -n +2 | head -n 3 >>123.txt.new &&
tail -n +4 123.txt >>123.txt.new &&
mv 123.txt.new 123.txt

head+ tail메소드를 와 결합 할 수 있습니다 sed. 대용량 파일의 경우 이 방법이 아마도 가장 빠를 것입니다.

<abc.txt tail -n +2 | head -n 3 | sed -i '3r /dev/stdin' 123.txt

이러한 모든 메서드는 이동된 임시 파일에 기록됩니다 123.txt(사용된 메서드도 마찬가지입니다 . 이는 뒤에서 일어나는 일이기 sed -i때문입니다 ).sed -i

답변4

ed내부 편집을 위해 및 사용 sed(bash 프롬프트에서):

ed -s 123.txt<<<$'3r !sed -n "2,4p" abc.txt\nw'

관련 정보