다음과 같은 필드를 포함하는 Java 클래스가 있습니다.
private int port;
private String portName;
private ArrayList portList;
private int id;
위의 블록을 터미널에 직접 붙여넣고 해당 명령 또는 스크립트에 대한 입력으로 제공하고 다음 출력을 제공 할 수 있도록 명령 또는 스크립트가 필요합니다.
public String toString() {
return "{ " + "port=" + port + ",portName=" + portName + ",portList=" + portList + ",id=" + id + "}";
}
사용하는 oneliner awk
(예 : GNU awk는)
awk 'BEGIN{printf"public String toString() {\n return \"{ \""}{gsub(";$","");printf" + \"";if(NR>1){printf","};printf$3"=\" + "$3}END{print" + \"}\";\n}"}'
다음과 같이 사용하십시오.
$ awk 'BEGIN{printf"public String toString() {\n return \"{ \""}{gsub(";$","");printf" + \"";if(NR>1){printf","};printf$3"=\" + "$3}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 + "}";
}
#!/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 $3"=\" + "$3
}
# do the following after processing the text
END {
# print ' + "}";\n}', '\n' is a line break
print " + \"}\";\n}"
}
예를 들어 저장하고 generate_toString
실행 가능하게 만들고 다음 chmod +x generate_toString
과 같이 사용하십시오.
$ ./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 + "}";
}
이것이 당신이 요청한 것을 수행하지만 실제 문제를 해결하기 위해 훨씬 더 나은 접근 방식 이 있습니다 . 위의 @nickb 주석 뿐만 아니라 @DavidFoerster를 참조하십시오 . 바퀴를 재발 명 할 필요가 없습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다