3

I want to concatenate the files whose name does not include "_BASE_". I thought it would be somewhere along the lines of ...

ls | grep -v _BASE_ | cat > all.txt

the cat part is what I am not getting right. Can anybody give me some idea about this?

3 Answers 3

4

Try this

ls | grep -v _BASE_ | xargs cat > all.txt
2

You can ignore some files with ls using --ignore option and then cat them into a file.

ls --ignore="*_BASE_*" | xargs cat > all.txt 

Also you can do that without xargs:

cat $( ls --ignore="*_BASE_*" ) > all.txt

UPD: Dale Hagglund noticed, that filename like "Some File" will appear as two filenames, "Some" and "File". To avoid that you can use --quoting-style=WORD option, when WORD can be shell or escape.

For example, if --quoting-style=shell Some File will print as 'Some File' and will be interpreted as one file.

Another problem is output file could the same of one of lsed files. We need to ignore it too.

So answer is:

outputFile=a.txt; ls --ignore="*sh*" --ignore="${outputFile}" --quoting-style=shell | xargs cat > ${outputFile}
1
  • Neither of these work if any of the filenames contains whitespace. A filename like "Some File" will appear as two filenames, "Some" and "File", when passed to cat. Dec 16, 2011 at 9:21
1

If you want to get also files from subdirectories, `find' is your friend:

find . -type f ! -name '*_BASE_*' ! -path ./all.txt -exec cat {} >> all.txt \+

It searches files in the current directory and its subdirectories, it finds only files (-type f), ignores files matching to wildcard pattern *_BASE_*, ignores all.txt, and executes cat in the same manner as xargs would.

4
  • +1 To limit to the current directory, add -maxdepth 1. This one should also cleanly handle files spaces in their name.
    – jackrabbit
    Dec 16, 2011 at 8:38
  • I'd quote the '_BASE_' part (doesn't work in zsh otherwise). Also prepend rm all.txt and do the redirection from cat with >>. The + at the end should probably be a ;
    – jackrabbit
    Dec 16, 2011 at 8:45
  • \+ is a deliberate choice to reduce the number of cats. Dec 18, 2011 at 15:43
  • Didn't know about that modifier. Cool!
    – jackrabbit
    Dec 18, 2011 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.