I am trying to get a couple of specific lines from files with a specific extension (.pvc). These files are stored in different directories. Then I want to put all the lines in a single txt file.



I am trying to use the following for loop but it doesn't work.

for i in {1..5}
 echo $i
 cd /home/directory"$i"
 grep -e L1 -e L2 /*.pvc > /home/all_lines.txt
  • grep -h 'L1|L2' ~/directory{1..5}/*.pvc >~/all_lines.txt – Satō Katsura Mar 13 '17 at 17:05
  • In your attempt you are overwriting all_lines.txt in each loop (if you have write pemissions in /home at all). Use >> instead of > to append instead. – Philippos Mar 13 '17 at 17:09
  • @Sato Katsura, By using the option -h I don't get nothing in the output file, but using -e L1 -e L2 it works but it also prints (in the output file) the path of the directories in each line. – Fersal Mar 13 '17 at 18:10
  • -h tells grep not to print filenames. This works with at least GNU grep and BSD grep. – Satō Katsura Mar 13 '17 at 18:23
  • It already works, I used -h along with -e. Thanks! – Fersal Mar 13 '17 at 18:32

Posting an answer as requested:

grep -h 'L1|L2' ~/directory{1..5}/*.pvc >~/all_lines.txt 

-h tells grep not to print filenames, L1|L2 searches for lines L1 and L2, and directory{1..5} expands to directory1, ..., directory5.


Are they all sub-directories inside a specific directory (father_directory)?

You can try:

find /father_directory -iname '*pvc' -exec grep -e L1 -e L2 {} \; > /home/all_lines.txt

or, as suggested by @Philippos (thank you):

grep -r /father_directory -e L1 -e L2 --include "*.pvc" > /home/all_lines.txt
  • 1
    Or even simpler with grep only: grep -r /father_directory -e L1 -e L2 --include "*.pvc" > /home/all_lines.txt – Philippos Mar 13 '17 at 17:12
  • They are into into sub-folders that in turns are into a common directory (I guess that would be the father_directory). – Fersal Mar 13 '17 at 18:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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