Comment a line in a file.log

3

Good, I have the following code:

 !/bin/bash

  while read line;
  do

  echo "$line";
   if[???????]
   fi

  done < /home/javi.log

javi.log file:

#

javi_2223
javi55_555
imp33
imp44
javi32423
javi5646

I want the script to comment on the lines imp33 and imp44 I would do with if but I do not know what to use to comment on them ...

It would be as follows:

#

javi_2223
javi55_555
#imp33
#imp44
javi32423
javi5646

if the file were like this: how would it be by putting: space does not catch me

javi_2223
javi55_555

#imp33
#imp44

javi32423
javi5646
    
asked by ortiga 19.12.2018 в 19:21
source

1 answer

11

Using bash

To obtain the best result in bash and to facilitate adding new terms I recommend you use case instead of if nested as follows:

#!/bin/bash

# read limpia espacios por delante y por detrás del texto
while read line
do
  # Dependiendo del contenido de $line ...
  case "$line" in
    imp33|imp44)
      # Si es "imp33" o "imp44" agregamos un # delante
      echo "#${line]"
      ;;
    *)
      # En caso contrario mostramos tal cual la línea
      echo "$line";
      ;;
  esac
done < /home/javi.log

Using sed

The most efficient way to do what you want is to use the sed tool using the following substitution pattern:

sed -r 's/^(imp33|imp44)$/#/' /home/javi.log

Of all the functionality offered by sed I used the function of "substitution" ( s of substitute ) that has the following format: s/patrón/sustitución/opciones . In my case I have not used any option, but you could use i , for example, so that the search is insensitive to upper and lower case.

On the online version you will see a description of how the pattern and capture groups work:

  • Start line ^ .
  • Capture group () :
    • option imp33 .
    • option imp44 .
  • End of line $ .

Whatever is on the line, if the capture pattern is met, it will be replaced by # which means:

  • A pad symbol # .
  • Content of the first capture group .

Unlike the version in bash , the characters in white before and after the text are not deleted, so if you want the behavior to be the same you should use the following pattern:

sed -r 's/^[[:space:]]*(imp33|imp44)[[:space:]]*$/#/' /home/javi.log

On the online version you will see a description of how the pattern and capture groups work:

  • Start line ^ .
  • 0 or more space characters, tabs, etc ( [ \t\r\n\v\f] ).
  • Capture group () :
    • option imp33 .
    • option imp44 .
  • 0 or more space characters, tabs, etc ( [ \t\r\n\v\f] ).
  • End of line $ .

Since the blank characters have not been included in the capture group, they will not be in the substitution, which will remain the% pil_de% character followed by the capture group.

  

You can learn more about how # works (thanks to    @Juan and @JackNavaRow for the   suggestion) on the following pages:

     
    
answered by 19.12.2018 / 19:32
source