
적응 중이에요이 스크립트한 파일의 내용을 다른 파일에 삽입합니다. 이것이 내가 지금 가지고 있는 것입니다:
#!/bin/sh
# Check if first and second parameters exist
if [ ! -z "$2" ]; then
STRING=$(cat $1)
# Check if the supplied file exist
if [ -e $2 ]; then
sed -i -e "2i$STRING" $2
echo "The string \"$STRING\" has been successfully inserted."
else
echo "The file does not exist."
fi
else
echo "Error: both parameters must be given."
fi
나는 그것을 다음과 같이 실행합니다 :./prepend.sh content.txt example.txt
파일 content.txt
:
first_line
second_line
파일 example.txt
:
REAL_FIRST_LINE
REAL_SECOND_LINE
스크립트의 출력:
sed: -e expression #1, char 24: unterminated `s' command
The string "first_line
second_line" has been successfully inserted.
그리고 파일 내용은 example.txt
다음과 같이 동일하게 유지됩니다.
REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE
답변1
당신이 원하는 것 같네요명령r
:
sed "1r $1" "$2"
GNU sed를 사용하면 이 작업을 수행할 수 있습니다.
cat "$1" | sed '2r /dev/stdin' "$2"
답변2
GNU 버전에서는 (읽기) 명령을 사용하여 파일 내용을 특정 라인 주소에 직접 읽고 삽입 sed
할 수 있습니다.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 '1r content.txt' example.txt
REAL_FIRST_LINE
first_line
second_line
REAL_SECOND_LINE