Intento reemplazar algunos textos en archivos de texto con sed
pero no sé cómo hacerlo con varios archivos.
Uso:
sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g /path/to/file/target_text_file
Antes de ir con los múltiples archivos, imprimí las rutas de los archivos de texto específicos en un archivo de texto con este comando:
find /path/to/files/ -name "target_text_file" > /home/user/Desktop/target_files_list.txt
Ahora quiero ejecutar sed
según target_files_list.txt
.
Respuesta aceptada:
Puede recorrer el archivo usando while ... do
bucle:
$ while read i; do printf "Current line: %s\n" "$i"; done < target_files_list.txt
En su caso, debe reemplazar printf ...
con sed
comando que desee.
$ while read i; do sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' "$i"; done < target_files_list.txt
Sin embargo, tenga en cuenta que puede lograr lo que desea usando solo find
:
$ find /path/to/files/ -name "target_text_file" -exec sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' {} \;
Puede leer más sobre -exec
opción ejecutando man find | less '+/-exec '
:
-exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead.
EDITAR:
Como lo señalaron correctamente los usuarios terdon y postre en los comentarios
es necesario usar -r
con read
porque manejará correctamente
las barras invertidas. También lo informa shellcheck
:
$ cat << EOF >> do.sh
#!/usr/bin/env sh
while read i; do printf "$i\n"; done < target_files_list.txt
EOF
$ ~/.cabal/bin/shellcheck do.sh
In do.sh line 2:
while read i; do printf "\n"; done < target_files_list.txt
^-- SC2162: read without -r will mangle backslashes.
Así debería ser:
$ while read -r i; do sed -i -- 's/SOME_TEXT/SOME_TEXT_TO_REPLACE/g' "$i"; done < target_files_list.txt