De acordo com as Leis 12.965/2014 e 13.709/2018, que regulam o uso da Internet e o tratamento de dados pessoais no Brasil, ao me inscrever na newsletter do portal DICAS-L, autorizo o envio de notificações por e-mail ou outros meios e declaro estar ciente e concordar com seus Termos de Uso e Política de Privacidade.
Justificador de texto com Sed
Colaboração: Aurélio Marinho Jargas
Data de Publicação: 21 de Julho de 2000
Sexta à noite, hoje não rolou show ou náite, então a ociosidade
me fez ser produtivo &:)
Aí nessa falta de algo de melhor pra fazer, fiz um carinha que
fazia tempo que eu queria, um justificador de texto.
Não é perfeito, mas funciona. pega um texto já quebrado no número
limite de colunas e apenas inclui uns espaços em branco aqui e
ali, da esquerda para a direita, palavra por palavra, até atingir
o limite máximo de colunas (no caso 65, que é o que eu uso aqui
no pine).
Se quiser usá-lo, basta:
$ chmod +x justifica.sed
$ ./justifica.sed arquivo.txt > arquivo-justificado.txt
Se quiser alterar, o número de colunas máximo, troque todos os 65
do script pelo número desejado.
Se quiser usar no vim, selecione o texto com o modo visual e
:'<,'>!justifica.sed
Ah! esta mensagem foi justificada por ele &:)
#!/bin/sed -f
# justify.sed
#
# it gets a text already wrapped on the desired number of columns
# and add extra white spaces, from left to right, word by word,
# to justify all the lines. there is a maximum of 5 spaces to be
# inserted between the words. if this limit is reached, the line
# is not justified (come on, more than 5 is horrible). empty
# lines are ignored. btw, this comments were justified with this
# script &:)
#
# 20000715
# we'll only justify lines with less than 65 chars
/^.\{65\}/!{
# cleaning extra spaces of the line
s/^ \+//
s/ \+/ /g
s/ \+$//
# don't try to justify blank lines
/^$/b
# backup of the line
h
# spaces -> pattern
# convert series of spaces to a internal pattern `n
:s2p
s/ /`5/g
s/ /`4/g
s/ /`3/g
s/ /`2/g
s/ /`1/g
t 1space
b
# pattern -> spaces
# restore the spaces converted to the internal pattern `n
:p2s
s/`5/ /g
s/`4/ /g
s/`3/ /g
s/`2/ /g
s/`1/ /g
t check
b
# check if we've reached our right limit
# if not, continue adding spaces
:check
/^.\{65\}/!b s2p
b
# here's the "magic":
# add 1 space to the first and minor internal pattern found.
# this way, the extra spaces are always added from left to right,
# always balanced, one by one.
# right after the substitution, we'll restore the spaces and
# test if our limit was reached.
:1space
s/""1/""2/ ; t p2s
s/""2/""3/ ; t p2s
s/""3/""4/ ; t p2s
s/""4/""5/ ; t p2s
# we don't want to justify with more than 5 added spaces between
# words, so let's restore the original line
/`5/x
}