Skip to content

Instantly share code, notes, and snippets.

@yeiichi
Created October 26, 2024 15:02
Show Gist options
  • Save yeiichi/137b30be26ab5055f253fe97dfb720e2 to your computer and use it in GitHub Desktop.
Save yeiichi/137b30be26ab5055f253fe97dfb720e2 to your computer and use it in GitHub Desktop.
Remove the first n characters from the file content.
#!/usr/bin/env zsh
# Reference:
# https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
display_help() {
cat <<EOF
*** Remove the first n characters from the file content. ***
Use me when dos2unix nor nkf doesn't work.
EOF
}
main() {
[[ "$1" == '--help' ]] && display_help
# Input
printf "\033[93mTarget file? >> \033[0m"
read -r file_in
[[ ! -f "$file_in" ]] && printf "\033[31mFile not found\033[0m" && return 1
printf "\033[93mNumber of chars to be removed? >> \033[0m"
read -r num
# Preparation
stem="${file_in%.*}"
suffix="${file_in##*.}"
file_out="$stem"_precessed."$suffix"
str_out=$(sed -r 1s/^.{"$num"}//g "$file_in")
# Confirm
printf "\033[93mTest output: \033[0m%s" "$str_out" | head -c 64
printf "\n\033[93mOK? (Y/n) >> \033[0m"
read -r res
# Execute
if [[ "$res" == [Yy] ]]; then
echo "$str_out" > "$file_out"
printf "\033[93mSaved:\033[0m %s\n" "$file_out"
else
printf "\033[31mExited\033[0m\n"
fi
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment