-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprepend
More file actions
executable file
·74 lines (69 loc) · 2.06 KB
/
Copy pathprepend
File metadata and controls
executable file
·74 lines (69 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env bash
# author: andreasl
show_help() {
script_name="${0##*/}"
msg="${script_name}\n"
msg+="Prepend a given file with a given string from stdin.\n"
msg+="\n"
msg+="Usage:\n"
msg+=" ${script_name} [OPTIONS] <file> -o <output-file> <<< <input-string>\n"
msg+=" echo <input-string> | ${script_name} <file> -o <output-file>\n"
msg+="\n"
msg+="Options:\n"
msg+=" -h, --help: Print the help message.\n"
msg+=" -i, --inline: Write output to same file as input file.\n"
msg+=" -o <file>, --output <file>: Write output to specified output file.\n"
msg+="\n"
msg+="Examples:\n"
msg+=" ${script_name} -i script.py <<< '#!/usr/env/bin python3\\\n# -*- coding: utf-8 -*-'\n"
msg+=" printf 'Step 0: ' | ${script_name} myfile.txt -o otherfile.txt\n"
printf "$msg"
}
inline=false
while [ "$#" -gt 0 ]; do
case "$1" in
-i | --inline)
inline=true
;;
-o | --output)
output_file="$2"
shift # past argument
;;
-h | --help)
show_help
exit 0
;;
*) # unknown option
input_file="$1"
;;
esac
shift # past argument or value
done
if [ -z "$input_file" ]; then
printf "Error: No input file specified.\n"
exit 1
fi
if [ "$inline" == true ]; then
output_file="$input_file"
fi
if [ -z "$output_file" ]; then
printf "Error: No output file specified.\n"
exit 1
fi
# read all of stdin at once; the sentinel `x` preserves trailing newlines.
# `read -N` would be shorter but needs Bash 4.1+, which macOS does not ship.
input_to_prepend="$(
cat
printf x
)"
input_to_prepend="${input_to_prepend%x}"
file_content="$(
cat "$input_file"
printf x
)"
file_content="${file_content%x}"
# `%b` expands escapes like `\n` in the prepended string, so we can have e.g. newlines in the
# prepended input.
# The file's own content goes through `%s`, so that nothing in it is interpreted at all.
printf '%b' "$input_to_prepend" >"$output_file"
printf '%s' "$file_content" >>"$output_file"