Daily Shaarli

All links of one day in a single page.

February 5, 2013

unix - SED: How can I replace a newline (\n)? - Stack Overflow

Dans la série "les problèmes que j'ai rencontrés, et qu'avoir la solution est bien pratique", je présente le problème du "parse new line" :

Concrètement, imaginez que vous devez, pour X ou Y raisons, "analyser" (venant de l'anglais "to parse" http://translate.google.fr/translate_t?q=to+parse) les "retours à la ligne" ("new line") pour les modifier en d'autres caractères (comme '\n', textuellement), un simple "sed 's/\n/mon_texte/g'" ne fonctionnera.

Ainsi, merci à StackOverFlow pour la réponse suivante :
sed ':a;N;$!ba;s/\n/mon_texte/g' mon_fichier.txt

Je copie simplement ici l'explication (principalement au cas où le lien meurt) :

This will read the whole file in a loop, then replaces the newline(s) with a space.

  1. create a label via :a
  2. append the current and next line to the pattern space via N
  3. if we are before the last line, branch to the created label $!ba ($! means not to do it on the last line (as there should be one final newline)).
  4. finally the substitution replaces every newline with a space on the pattern space (which is the whole file).

Il existe aussi tr :
tr '\n' ' ' < mon_fichier.txt

Mais tr ne remplace que par un SEUL caractère ... dommage.

Pour ceux qui veulent en savoir plus, un commentaire un peu plus bas explique bien mieux http://stackoverflow.com/a/7697604