1
1
I am trying to put all js files in a directory and sub directorys into a single file in lexical order. What did I do wrong?
1
1
I am trying to put all js files in a directory and sub directorys into a single file in lexical order. What did I do wrong?
0
grep
is the wrong tool for this, partly because it only emits lines from those files that match the pattern you give (and presumably you want all the lines), and partly because you didn't give a pattern, so it's using the first filename as the pattern (which is not helpful).
Listing all *.js
files is easy enough:
find . -name '*.js'
And concatenating them into one file is easy too:
find . -name '*.js' | xargs cat
But, sorting them according to lexical order of just the filename, disregarding whatever directory they may be in, is harder.
Just plain sort
won't do the job, and there's no --key
option that will select the last field when the number of fields is unknown.
The following uses sed to move the filename to the start of the line, sorts that, and then strips it back off again.
find . -name '*.js' | sed 's:^.*/\([^/]*\)$:\1 \0:' | sort | cut -d' ' -f2-
This will not work correctly if any of your file or directory names have spaces.
You can then extract the contents by adding a cat
:
find . -name '*.js' \
| sed 's:^.*/\([^/]*\)$:\1 \0:' | sort | cut -d' ' -f2- \
| xargs cat
2Would
cat $(find ./ -type f -name "*.js" | sort) > dirname/.filename
work for you? – txtechhelp – 2015-10-18T21:53:27.257@txtechhelp thanks. it is close but files named 2.js and 3.js are being put above a file /dirname/1.js. If that can be fixed it would work great. – user5448026 – 2015-10-18T22:02:56.823
I can just put a 1 in front of the dir name but it would be good not to have to do that. – user5448026 – 2015-10-18T22:35:55.720
Do you need to include the dirname in your list ? Or do you need to have just the file names wherever they come from ? – None – 2015-10-19T09:07:09.560