Programing

파일 앞에 텍스트를 추가하는 Unix 명령

lottogame 2020. 8. 12. 22:07
반응형

파일 앞에 텍스트를 추가하는 Unix 명령


텍스트 파일에 일부 문자열 데이터를 추가하는 Unix 명령이 있습니까?

다음과 같은 것 :

prepend "to be prepended" text.txt

sed -i.old '1s;^;to be prepended;' inFile
  • -i변경 사항을 기록하고 확장이 제공되면 백업을 수행합니다. (이 경우 .old)
  • 1s;^;to be prepended;;명령 구분 기호로 사용하여 첫 번째 줄의 시작 부분을 지정된 대체 문자열로 대체합니다 .

printf '%s\n%s\n' "to be prepended" "$(cat text.txt)" >text.txt

프로세스 대체

아무도 이것을 언급하지 않았다는 것에 놀랐습니다.

cat <(echo "before") text.txt > newfile.txt

이것은 받아 들여진 대답보다 더 자연 스럽습니다 (무언가를 인쇄하고이를 대체 명령에 연결하는 것은 사 전적으로 반 직관적입니다).

... 위에서 라이언이 말한 것을 납치 sponge하면 임시 파일이 필요하지 않습니다.

sudo apt-get install moreutils
<<(echo "to be prepended") < text.txt | sponge text.txt

편집 : Bourne Shell에서 작동하지 않는 것 같습니다. /bin/sh


Here String (zsh 전용)

here-string-사용하여 <<<다음을 수행 할 수 있습니다.

<<< "to be prepended" < text.txt | sponge text.txt

이것은 한 가지 가능성입니다.

(echo "to be prepended"; cat text.txt) > newfile.txt

중간 파일을 쉽게 다룰 수 없을 것입니다.

대안 (셸 이스케이프로 인해 번거로울 수 있음) :

sed -i '0,/^/s//to be prepended/' text.txt

이것은 출력을 형성하는 데 작동합니다. -는 에코에서 파이프를 통해 제공되는 표준 입력을 의미합니다.

echo -e "to be prepended \n another line" | cat - text.txt

파일을 다시 쓰려면 입력 파일로 다시 파이프 할 수 없으므로 임시 파일이 필요합니다.

echo "to be prepended" | cat - text.txt > text.txt.tmp
mv text.txt.tmp text.txt

Adam의 답변 선호

스펀지 를 사용하기 쉽게 만들 수 있습니다 . 이제 임시 파일을 만들고 이름을 바꿀 필요가 없습니다.

echo -e "to be prepended \n another line" | cat - text.txt | sponge text.txt

아마도 내장 된 것은 없지만 다음과 같이 꽤 쉽게 작성할 수 있습니다.

#!/bin/bash
echo -n "$1" > /tmp/tmpfile.$$
cat "$2" >> /tmp/tmpfile.$$
mv /tmp/tmpfile.$$ "$2"

적어도 그런 건 ...


입력 파일교체 할 수 있는 경우 :

참고 : 이렇게하면 예기치 않은 부작용이 발생할 수 있습니다 . 특히 심볼릭 링크를 일반 파일로 바꾸고 파일에 대한 다른 권한을 갖게 되며 파일 생성 (생년월일)이 변경 될 수 있습니다 .

sed -i, Prince John Wesley의 답변 에서와 같이 최소한 원래 권한을 복원하려고 시도하지만 다른 제한 사항이 적용됩니다 .

 { printf 'line 1\nline 2\n'; cat text.txt; } > tmp.txt && mv tmp.txt text.txt

참고 : 그룹 명령을 { ...; ... }사용하는 것이 하위 셸 ( (...; ...))을 사용하는 것보다 더 효율적 입니다.


입력 파일 을 제자리에서 편집해야하는 경우 (모든 속성과 함께 inode를 유지) :

오래된 edPOSIX 유틸리티 사용 :

Note: ed invariably reads the input file as a whole into memory first.

ed -s text.txt <<'EOF' 
1i
line 1
line 2
.
w
EOF
  • -s suppressed ed's status messages.
  • Note how the commands are provided to ed as a multi-line here-document (<<'EOF' ... EOF), i.e., via stdin.
  • 1i makes 1 (the 1st line) the current line and starts insert mode (i).
  • The following lines are the text to insert before the current line, terminated with . on its own line.
  • w writes the result back to the input file (for testing, replace w with ,p to only print the result, without modifying the input file).

In some circumstances prepended text may available only from stdin. Then this combination shall work.

echo "to be prepended" | cat - text.txt | tee text.txt

If you want to omit tee output, then append > /dev/null.


Solution:

printf '%s\n%s' 'text to prepend' "$(cat file.txt)" > file.txt

Note that this is safe on all kind of inputs, because there are no expansions. For example, if you want to prepend !@#$%^&*()ugly text\n\t\n, it will just work:

printf '%s\n%s' '!@#$%^&*()ugly text\n\t\n' "$(cat file.txt)" > file.txt

The last part left for consideration is whitespace removal at end of file during command substitution "$(cat file.txt)". All work-arounds for this are relatively complex. If you want to preserve newlines at end of file.txt, see this: https://stackoverflow.com/a/22607352/1091436


Another way using sed:

sed -i.old '1 {i to be prepended
}' inFile

If the line to be prepended is multiline:

sed -i.old '1 {i\ 
to be prepended\
multiline
}' inFile

As tested in Bash (in Ubuntu), if starting with a test file via;

echo "Original Line" > test_file.txt

you can execute;

echo "$(echo "New Line"; cat test_file.txt)" > test_file.txt

or, if the version of bash is too old for $(), you can use backticks;

echo "`echo "New Line"; cat test_file.txt`" > test_file.txt

and receive the following contents of "test_file.txt";

New Line
Original Line

No intermediary file, just bash/echo.


Another fairly straight forward solution is:

    $ echo -e "string\n" $(cat file)

If you like vi/vim, this may be more your style.

printf '0i\n%s\n.\nwq\n' prepend-text | ed file

# create a file with content..
echo foo > /tmp/foo
# prepend a line containing "jim" to the file
sed -i "1s/^/jim\n/" /tmp/foo
# verify the content of the file has the new line prepened to it
cat /tmp/foo

I'd recommend defining a function and then importing and using that where needed.

prepend_to_file() { 
    file=$1
    text=$2

    if ! [[ -f $file ]] then
        touch $file
    fi

    echo "$text" | cat - $file > $file.new

    mv -f $file.new $file
}

Then use it like so:

prepend_to_file test.txt "This is first"
prepend_to_file test.txt "This is second"

Your file contents will then be:

This is second
This is first

I'm about to use this approach for implementing a change log updater.

참고URL : https://stackoverflow.com/questions/10587615/unix-command-to-prepend-text-to-a-file

반응형