![STDIN의 텍스트를 파일 시작 부분에 추가하는 방법](https://linux55.com/image/189947/STDIN%EC%9D%98%20%ED%85%8D%EC%8A%A4%ED%8A%B8%EB%A5%BC%20%ED%8C%8C%EC%9D%BC%20%EC%8B%9C%EC%9E%91%20%EB%B6%80%EB%B6%84%EC%97%90%20%EC%B6%94%EA%B0%80%ED%95%98%EB%8A%94%20%EB%B0%A9%EB%B2%95.png)
어떤 종류의 문제를 디버깅하려고 합니다.닉스Debian 기반 운영 체제의 Linux 설치 프로그램 스크립트
말했듯이여기, 이 스니펫은 다음과 같습니다 /etc/bash.bashrc
.
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
일부 Nix 명령은 비대화형 셸에서 실행되므로 코드 조각 전에 가져와야 하므로 일부 Nix 명령이 무효화됩니다.
예를 들어 이 명령을 생각해 냈는데 한 가지 예외를 제외하고는 잘 작동합니다.
sudo sed -i '1i source /etc/profile.d/nix.sh' /etc/bash.bashrc
Nix 스크립트에서 init 함수는 이미 함수에 의해 제공되고 함수의 명령 shell_source_lines()
에 파이프되어 파일을 추가하므로 파이프를 유지하면서 시작 부분을 추가해야 합니다.configure_shell_profile()
tee -a
shell_source_lines() {
cat <<EOF
# Nix
if [ -e '$PROFILE_NIX_FILE' ]; then
. '$PROFILE_NIX_FILE'
fi
# End Nix
EOF
}
configure_shell_profile() {
for profile_target in "${PROFILE_TARGETS[@]}"; do
if [ -e "$profile_target" ]; then
_sudo "to back up your current $profile_target to $profile_target$PROFILE_BACKUP_SUFFIX" \
cp "$profile_target" "$profile_target$PROFILE_BACKUP_SUFFIX"
else
# try to create the file if its directory exists
target_dir="$(dirname "$profile_target")"
if [ -d "$target_dir" ]; then
_sudo "to create a stub $profile_target which will be updated" \
touch "$profile_target"
fi
fi
# What I need to modify :
if [ -e "$profile_target" ]; then
shell_source_lines \
| _sudo "extend your $profile_target with nix-daemon settings" \
tee -a "$profile_target" # Needs to be replaced
fi
done
}
파일 앞에 STDIN 텍스트를 추가하는 방법을 찾을 수 없습니다. 이를 수행할 수 있는 방법이 있습니까?
답변1
이 명령을 GNU sed 버전으로 바꾸십시오.
tee -a "$profile_target"
sed -i -e '1r /dev/stdin' -e '1N' "$profile_target"
- 최소한 2줄의 입력을 가정합니다.
답변2
cat /dev/stdin file.txt
stdin에서 입력을 받아 stdout에 쓴 다음 file.txt
.
예를 들어 다음을 file.txt
포함하는 경우(행 번호는 설명을 위한 것일 뿐이며 파일 내용의 일부가 아닙니다)
1 This is some text in the
2 text file.
3 It has three lines.
그 다음에
echo "Prepended text line" | cat /dev/stdin file.txt > combined.txt
결과 파일에는 다음 combined.txt
이 포함됩니다.
1 Prepended text line
2 This is some text in the
3 text file.
4 It has three lines.
답변3
파일 시작 부분에 줄을 추가하는 것은 말만큼 쉽지 않으며 종종 sed -i
임시 파일이 뒤에서 사용됩니다(완료된 것처럼).
cat > data.new && mv data.new "$profile_target"
또는 더 빠른 솔루션을 위해서는 외부 도구( )가 필요 sponge
합니다 moreutils
.
cat - "$profile_target" | sponge "$profile_target"
노트:
입력이 비어 있는지(stdin에서) 확인하지 않습니다. 비어 있는 경우 파일 시작 부분에 공백/공백을 추가하기 때문입니다.
또한 어떤 종류의 처리 오류도 발생하지 않습니다. 따라서 이를 사용하는 모든 파일을 백업하거나 보다 안전한 방법을 사용하십시오.