2

As an example below, let's say the line I want to delete contains the string "X". How do I delete that line in each respective file, say, in a loop? Can I do this using grep and sed, or any other shell/bash program for that matter?

Line  File 1  File 2
   1       A       A
   2       B       B
   3       X       C
   4       C       X
   5       D       D
   6       E       X
   7       X       E
Joaquin
  • 2,013
  • 3
  • 14
  • 26

1 Answers1

6

In case you want to simple remove a line which has character "X" in it then this Simple grep command to rescue here:

grep -v "X"   Input_file

Adding sed solution too now, which will change Input_file itself:

sed -i.bak '/X/d'  file*
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • 2
    You could mention something on how to use `grep` to change an existing file. – Alfe Feb 15 '18 at 09:41
  • @Alfe, apologies if missed something here, but I am not aware of any option where `grep` could save the changes in file itself, please do let me know if there is any, always open for learning :) – RavinderSingh13 Feb 15 '18 at 09:48
  • 1
    @RavinderSingh13: Use `sed` for inline saving: `sed -i.bak '/X/d' file` – anubhava Feb 15 '18 at 09:50
  • 1
    `grep` indeed doesn't have such an option (except maybe in some weird system's variant of `grep`, I surely don't know all of them). But you always can redirect its output in a new file and later rename that to the original (`grep -v "X" Input_file > x && mv x Input_file`). I had the feeling OP was searching for this. – Alfe Feb 15 '18 at 09:51
  • 2
    @anubhava, sure sir you mean `sed -i.bak '/X/d' file*` since OP told many files are there :) – RavinderSingh13 Feb 15 '18 at 09:52
  • @Alfe, sure Alfe but that could be good for 1 Input_file for multiple we may have to take different approach too or please correct me if I am wrong here. – RavinderSingh13 Feb 15 '18 at 09:53
  • 1
    Thank you! :) I completely overlooked the grep -v command here. And yes, @Alfe you're right. I was thinking of redirecting outputs to another file and do the process recursively. Thanks all! :) – ajthealchemist Feb 15 '18 at 09:57
  • 1
    @RavinderSingh13 The solution with grep would handle one file, right. You can then put it inside a loop to process more than one file. That approach is called "Separation Of Concerns". – Alfe Feb 15 '18 at 10:48