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
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: