简体   繁体   中英

remove the last n lines from all files of a certain type in the current directory, recursive

I have the following bash script.

for i in **/*.h; do head $i -n -2 > $i.tmp && mv $i.tmp $i -f; done

The purpose is to run over every .h file inside the current directory and remove the last two lines from that file.

However this does only work as intended on files that are located directly in subfolders of the current directory, but it doesn't process files inside subfolder of subfolders and so on, so ./foo/foobar.h gets processed, but ./foo/bar/foobar.h or for/bar/foobar/.foobar.h don't.

Therefor I have tried it this way:

for i in 'find -name *.h'; do head $i -n -2 > $i.tmp && mv $i.tmp $i -f; done

This fails, because > $i.tmp is ambiguous

How should my script look so that it processes all the header files in a directory, no matter, how deeply they are nested in subfolders?

EDIT: If the original file hasn't had a newline directly before eof, the working first script from above (and also the sed alternative from the answers) will add one, so if a newline before eof isn't desired, it has to be removed afterwards:

for i in **/*.h; do head $i -n -2 > $i.tmp && mv $i.tmp $i -f && truncate --size=-2 $i; done

size should be -2 for CRLF (Windows style) newline and -1 for both, CR (old MacOS style) and LF (unix style), line endings

Of course this approach will also remove a newline before eof, that has already been there before

Your first snippet should work if you have and

shopt -s globstar

enabled.

globstar

If set, the pattern '**' used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a '/', only directories and subdirectories match.

See http://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html

find -name '*.h' -exec sed -i 'N;$!P;$!D;$d' '{}' ';'

This will delete the last two lines from all .h files, and eliminates the need for redirection and temp files, since it edits the files in place. It will also work with filenames and paths that contain spaces.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM