I would like to append a line including date of file modification to all .sh files.
To append variable text to all .sh files:
find -name "*.sh" -exec sed -i '$a \\n# '"$date"'' {} \;
To get the year of file modification:
find -name "*.sh" -exec stat -c %y {} \; | awk '{print $1}' | awk -F- '{print $1}'
How do I combine these to get the year for each file and insert it into the file contents?
CodePudding user response:
This find one-liner might be what you want:
find -name '*.sh' -exec bash -c 'printf "# %(%Y)T\n" $(stat -c %Y "$1") >> "$1"' _ {} \;
assuming you have stat from GNU coreutils.
The bash syntax to execute a command string is bash -c command_string arg_0 arg_1 ... arg_n (args are optional). arg_0 corresponds to bash special parameter $0, arg_1 corresponds to bash special parameter $1, and so on, within the command string. For each file the find finds, the {} is replaced with the pathname and the bash command is executed. The string _ is assigned to $0 (it normally stands for the name of the shell or shell script, which doesn't interest us here because we're running a command string, not a file), and the pathname is assigned to the $1, then the command printf "# %(%Y)T\n" $(stat -c %Y "$1") >> "$1" is executed. stat -c %Y prints out the time of last data modification as seconds since Epoch and the format specification %(%Y)T in printf builtin of bash interprets this value as a year.
CodePudding user response:
Using GNU find and GNU awk and assuming you don't have newlines or leading/trailing white space in your file names
while read -r year file; do
awk -i inplace -v year="$year" '{print} ENDFILE{print "#", year}' "$file"
done < <(find . -type f -name '*.sh' -printf '%TY %p\n')
You could do it more efficiently with just a pipe from find to awk and then modifying ARGV[] to create the file list, and you could make it able to handle newlines in the names but it's more code and I'm too lazy.
