I am trying to put all .js
files in a directory and sub directories into a single file in lexical order. I have tried:
grep -r --include=*.js * > dir/.filename
What did I do wrong?
You can use find
to find the files and then sort
to sort the names:
find . -type f -name '*.js' | sort
To save the names in a file:
find . -type f -name '*.js' | sort >files.txt
Let's analyze your command:
grep -r --include=*.js *
You need to put a directory name as argument while using -r
option e.g. (also put ''
around glob match so that they don't produce unexpected results):
grep -r --include='*.js' .
This would look for non-empty files i.e. this is equivalent to:
grep -r --include='*.js' '.' .
If you want to check for a specific pattern e.g. lines starting with TERM
:
grep -r --include='*.js' '^TERM' .
Anyway the main point is grep
is searching the file contents for any match but your goal is to match against the file names so you should go for something else that can do that e.g. find
or a shell loop.
You can also use the globstar
option of bash
to search for files ending in .js
recursively and then sort them using sort
.
At first you need to enable the globstar
option of bash
:
shopt -s globstar
Now **/*.js
will find the files (and directories) with .js
extension.
So the following should do the trick:
for i in **/*.js; do [[ -f $i ]] && echo "$i"; done
[[ -f $i ]]
is there to ensure that we are dealing with only files on output.
grep
is a line matching tool. It is suitable for searching contents of a file, but not searching files themselves.
Use find
command to do that. Find is recursive by default and has many many options for optimizing search.
For instance, if I wanted to recursively find all of the regular files (not directories) with extension *.png
recursively from /home
directory and down to the subdirectories, I would tell find
to start from /home
directory, search for files with -type
, and use case-insensetive matching with -iname
for files that end in ".png".
xieerqi:$ find /home -type f -iname "*.png" | head
/home/xieerqi/Downloads/35457542.png
/home/xieerqi/genymotion/icons/icon.png
/home/xieerqi/chinese-calendar-0.8.2/skin/default/ok.png
/home/xieerqi/chinese-calendar-0.8.2/skin/default/no.png
/home/xieerqi/chinese-calendar-0.8.2/skin/default/note.png
/home/xieerqi/chinese-calendar-0.8.2/skin/default/chinesecalendarBGyellow.png
/home/xieerqi/chinese-calendar-0.8.2/skin/blue/ok.png
/home/xieerqi/chinese-calendar-0.8.2/skin/blue/no.png
/home/xieerqi/chinese-calendar-0.8.2/skin/blue/note.png
/home/xieerqi/chinese-calendar-0.8.2/skin/blue/chinesecalendarBGblue.png
.js
extension recursively?gulp-concat
concatenates all files, then minify or something else.