Programming

sed 또는 awk를 사용하여 특정 줄 번호에 줄을 삽입하십시오.

procodes 2020. 6. 29. 21:44
반응형

sed 또는 awk를 사용하여 특정 줄 번호에 줄을 삽입하십시오.


8 번째 줄에 텍스트를 삽입하기 위해 다른 스크립트로 수정해야하는 스크립트 파일이 있습니다.

문자열 삽입 : Project_Name=sowstest라는 파일에 start.

나는 awk와 sed를 사용하려고했지만 내 명령이 깨졌습니다.


sed -i '8i8 This is Line 8' FILE

라인 8에 인서트

8 This is Line 8

파일 FILE에

-i glenn jackman의 의견에서 언급했듯이 파일 FILE에 직접 수정하고 stdout에 출력하지 않습니다.


ed대답

ed file << END
8i
Project_Name=sowstest
.
w
q
END

.자체 라인에서 입력 모드를 종료합니다. w쓰기; q피장 ​​장이 된. GNU ed에는 wq저장하고 종료하라는 명령이 있지만, ed는 그렇지 않습니다.

추가 읽기 : https://gnu.org/software/ed/manual/ed_manual.html


정답

awk -v n=8 -v s="Project_Name=sowstest" 'NR == n {print s} {print}' file > file.new

POSIX sed(및 예를 들어 sed, sed아래 의 OS X )에는 i백 슬래시와 줄 바꾸기가 있어야 합니다. 또한 적어도 OS X sed에는 삽입 된 텍스트 뒤에 줄 바꿈이 포함되어 있지 않습니다.

$ seq 3|gsed '2i1.5'
1
1.5
2
3
$ seq 3|sed '2i1.5'
sed: 1: "2i1.5": command i expects \ followed by text
$ seq 3|sed $'2i\\\n1.5'
1
1.52
3
$ seq 3|sed $'2i\\\n1.5\n'
1
1.5
2
3

행을 바꾸려면 c(change) 또는 s(substitute) 명령을 숫자 주소와 함께 사용할 수 있습니다 .

$ seq 3|sed $'2c\\\n1.5\n'
1
1.5
3
$ seq 3|gsed '2c1.5'
1
1.5
3
$ seq 3|sed '2s/.*/1.5/'
1
1.5
3

다음을 사용하는 대안 awk:

$ seq 3|awk 'NR==2{print 1.5}1'
1
1.5
2
3
$ seq 3|awk '{print NR==2?1.5:$0}'
1
1.5
3

awk다음을 -v사용하여 전달 된 변수가 아닌 전달 된 변수의 백 슬래시를 해석합니다 ENVIRON.

$ seq 3|awk -v v='a\ba' '{print NR==2?v:$0}'
1
a
3
$ seq 3|v='a\ba' awk '{print NR==2?ENVIRON["v"]:$0}'
1
a\ba
3

모두 ENVIRON-vPOSIX에 의해 정의됩니다.


OS X / macOS sed

-i플래그는 sedGNU 와 macOS 에서 다르게 작동합니다 sed.

macOS / OS X에서 사용하는 방법은 다음과 같습니다.

sed -i '' '8i\
8 This is Line 8' FILE

자세한 내용 man 1 sed참조하십시오 .


펄 솔루션 :

빠르고 더러운 :

perl -lpe 'print "Project_Name=sowstest" if $. == 8' file

  • -l strips newlines and adds them back in, eliminating the need for "\n"
  • -p loops over the input file, printing every line
  • -e executes the code in single quotes

$. is the line number

equivalent to @glenn's awk solution, using named arguments:

perl -slpe 'print $s if $. == $n' -- -n=8 -s="Project_Name=sowstest" file

  • -s enables a rudimentary argument parser
  • -- prevents -n and -s from being parsed by the standard perl argument parser

positional command arguments:

perl -lpe 'BEGIN{$n=shift; $s=shift}; print $s if $. == $n' 8 "Project_Name=sowstest" file

environment variables:

setenv n 8 ; setenv s "Project_Name=sowstest"
echo $n ; echo $s
perl -slpe 'print $ENV{s} if $. == $ENV{n}' file

ENV is the hash which contains all environment variables

Getopt to parse arguments into hash %o:

perl -MGetopt::Std -lpe 'BEGIN{getopt("ns",\%o)}; print $o{s} if $. == $o{n}' -- -n 8 -s "Project_Name=sowstest" file

Getopt::Long and longer option names

perl -MGetopt::Long -lpe 'BEGIN{GetOptions(\%o,"line=i","string=s")}; print $o{string} if $. == $o{line}' -- --line 8 --string "Project_Name=sowstest" file

Getopt is the recommended standard-library solution.
This may be overkill for one-line perl scripts, but it can be done


For those who are on SunOS which is non-GNU, the following code will help:

sed '1i\^J
line to add' test.dat > tmp.dat
  • ^J is inserted with ^V+^J
  • Add the newline after '1i.
  • \ MUST be the last character of the line.
  • The second part of the command must be in a second line.

sed -e '8iProject_Name=sowstest' -i start using GNU sed

Sample run:

[root@node23 ~]# for ((i=1; i<=10; i++)); do echo "Line #$i"; done > a_file
[root@node23 ~]# cat a_file
Line #1
Line #2
Line #3
Line #4
Line #5
Line #6
Line #7
Line #8
Line #9
Line #10
[root@node23 ~]# sed -e '3ixxx inserted line xxx' -i a_file 
[root@node23 ~]# cat -An a_file 
     1  Line #1$
     2  Line #2$
     3  xxx inserted line xxx$
     4  Line #3$
     5  Line #4$
     6  Line #5$
     7  Line #6$
     8  Line #7$
     9  Line #8$
    10  Line #9$
    11  Line #10$
[root@node23 ~]# 
[root@node23 ~]# sed -e '5ixxx (inserted) "line" xxx' -i a_file
[root@node23 ~]# cat -n a_file 
     1  Line #1
     2  Line #2
     3  xxx inserted line xxx
     4  Line #3
     5  xxx (inserted) "line" xxx
     6  Line #4
     7  Line #5
     8  Line #6
     9  Line #7
    10  Line #8
    11  Line #9
    12  Line #10
[root@node23 ~]# 

참고URL : https://stackoverflow.com/questions/6537490/insert-a-line-at-specific-line-number-with-sed-or-awk

반응형