Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I use ubuntu 14.4, and attempt to redirect the output of grep command to a file, but I keep getting this error:

grep: input file 'X' is also the output

I've searched for this issue and just found out that it was a bug in ubuntu 12.4 and there is not any describe about, can anybody help me to figure out this problem?

I run the following command:

grep -E -r -o -n r"%}(.*){%" > myfile
share|improve this question
    
If you are trying grep pattern file > file then it doesn't work. You cannot use the same file as input and output for grep. –  jimmij Oct 25 '14 at 21:29
    
i add my command ! thanks for hint , but when i try to use a file in other path the does not predicate it and i cant do that ! –  Kasra Oct 25 '14 at 21:34
    
for example with ../f i get this bash: ../f.txt: Permission denied –  Kasra Oct 25 '14 at 21:37
    
show full command, what is your input file, or are you using the pipe? –  jimmij Oct 25 '14 at 21:42
    
Yes, please show the entire command. It's unclear what you're asking us at this point, so unlikely that anyone will be able to help you further. –  slm Oct 25 '14 at 21:43

1 Answer 1

up vote 2 down vote accepted

It is not possible to use the same file as input and output for grep. You may consider the following alternatives:

  • temporary file

    grep pattern file > tmp_file
    mv tmp_file file
    
  • sed

    sed -i -n '/pattern/p' file
    
  • put whole file in the variable (not bright idea for large files)

    x=$(cat file); echo "$x" | grep pattern > file
    
share|improve this answer
    
sed can be more portable sed -i '/pattern/!d' file –  Costas Oct 25 '14 at 21:53
    
But in the case OP wants sed -i -n 's/.*\(pattern\).*/\1/p' file –  Costas Oct 25 '14 at 22:20
    
@Costas you are right, the question was edited and additional info added so one can polish sed syntax as well. –  jimmij Oct 25 '14 at 22:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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