파일의 특정 줄에 텍스트를 추가하는 데 사용할 수있는 UNIX 명령은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/602921

  •  03-07-2019
  •  | 
  •  

문제

누구든지 누군가가 파일의 특정 줄 끝에 텍스트를 추가 할 수있는 일련의 UNIX 명령을 알고 있습니까?

예를 들어

라인 1

라인 2

3 행

4 행

파일이 다음과 같이 보이도록 텍스트 ", 추가 정보"를 3 행에 추가하고 싶습니다.

라인 1

라인 2

3 행, 추가 정보

4 행

도움이 되었습니까?

해결책

Perl:

perl -p -e's{\n}{, extra information\n} if $. ==3' myfile

$. is the line number

다른 팁

in awk it's:

awk '{s=$0; if( NR==3 ){ s=s ", Extra Information" } print s;}' myfile > newfile

proper sed version:

sed -e '3s/$/, Extra Information/' -i myfile

Here is a version with portable sed (without -i option):

sed '3s/$/Hello World/' myfile

Note that myfile is not modified, so you can recover from possible mistakes.

awk 'NR == 3 { print $0 ", extra information" } NR != 3' myfile

The part before the braces is the condition: If we are in line 3, we append some text. If braces are omitted, the default action is to just print out $0. Redirect to a new file or pipe to another program as appropriate. You cannot redirect to the same file you are just reading. A common workaround is to redirect to a new file, and then move over if the command was successful:

somecommand > oldfile.tmp && mv oldfile.tmp oldfile
sed -e "s/^Line 3/\0, extra info/" -i text.txt

If you want the extra information to be appended to just one line, any of the sed/awk one-liners will do.

If you want to append something to (almost) every line in the file, you should create a second file with the extra information for each line and use paste:

$ cat myfile
line 1
line 2
line 3
line 4
$ cat extra 
something

something else
$ paste myfile extra
line 1  something
line 2
line 3  something else
line 4
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top