Um oneliner usando awk
(ou seja, GNU Awk):
awk 'BEGIN{printf"public String toString() {\n return \"{ \""}{gsub(";$","");printf" + \"";if(NR>1){printf","};printf"=\" + "}END{print" + \"}\";\n}"}'
Use assim:
$ awk 'BEGIN{printf"public String toString() {\n return \"{ \""}{gsub(";$","");printf" + \"";if(NR>1){printf","};printf"=\" + "}END{print" + \"}\";\n}"}' <<EOF
> private int port;
> private String portName;
> private ArrayList portList;
> private int id;
> EOF
public String toString() {
return "{ " + "port=" + port + ",portName=" + portName + ",portList=" + portList + ",id=" + id + "}";
}
Versão do script com comentários explicativos
#!/usr/bin/awk -f
# do the following before processing the text
BEGIN {
# print this text, '\n' is a line break and '\"' a literal '"'
printf "public String toString() {\n return \"{ \""
}
{
# remove semicolon at the end of the line
gsub(";$","");
# print ' + "'
printf " + \"";
# if the line number is > 1 print ','
if (NR > 1) { printf "," };
# print the third row followed by '=" + ' and the third row again
printf "=\" + "
}
# do the following after processing the text
END {
# print ' + "}";\n}', '\n' is a line break
print " + \"}\";\n}"
}
Salvar como, por exemplo, generate_toString
, torne-o executável com chmod +x generate_toString
e use-o da seguinte forma:
$ ./generate_toString <<EOF
> private int port;
> private String portName;
> private ArrayList portList;
> private int id;
> EOF
public String toString() {
return "{ " + "port=" + port + ",portName=" + portName + ",portList=" + portList + ",id=" + id + "}";
}
Enquanto isso faz o que você pediu, para resolver seu problema real existem longe melhores abordagens, veja @ DavidFoerster e também por dessert 26.11.2017 / 01:12