1

I have a folder that contains text files. I need to extract lines that has 'BA' from these text files . I used grep command to print the lines with BA. I would like to save the outputs to another folder with the same file names. How can I change the following code?

grep "  BA  "  dir/*.txt

2 Answers 2

2
for i in dir/*.txt; do
   grep "  BA  " $i > $newdir/`basename $i`
done

Note the use of basename, which takes dir/a.txt (say) and returns a.txt

Sign up to request clarification or add additional context in comments.

Comments

1

Sounds like a job for GNU parallel:

parallel --dry-run grep '"  BA  "' '{} > otherdir/{/}' ::: dir/{a,b,c}.txt

Output:

grep "  BA  " dir/a.txt > otherdir/a.txt
grep "  BA  " dir/b.txt > otherdir/b.txt
grep "  BA  " dir/c.txt > otherdir/c.txt

Remove --dry-run when you're happy with what you see.

{} is replaced by the inputs after ::: (these can also come from stdin or a file), {/} is the basename of {}.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.