我不擅长Linux。 我正在使用下一个命令来查找一些数据:
svn info -R https://SOME_URL/TEST | grep 'Ruta: \|Fecha de último cambio: '
我得到的输出如下所示:
Ruta: TEST Fecha de último cambio: 2016-04-07 15:52:40 -0500 (jue 07 de abr de 2016) Ruta: PRUEBA1.txt Fecha de último cambio: 2016-04-07 15:16:19 -0500 (jue 07 de abr de 2016) Ruta: PRUEBA2.txt Fecha de último cambio: 2016-04-07 15:15:47 -0500 (jue 07 de abr de 2016)
但是我需要提交一份报告,所以我想看到输出为CSV文件,如下所示:
"Ruta";"Fecha" "TEST";"2016-04-07 15:52:40 -0500 (jue 07 de abr de 2016)" "PRUEBA1.txt";"2016-04-07 15:16:19 -0500 (jue 07 de abr de 2016)" "PRUEBA2.txt";"2016-04-07 15:15:47 -0500 (jue 07 de abr de 2016)"
只有使用linux命令才能做到这一点? 谢谢!
这个工作的正确工具是awk,当你使用awk的时候你不需要grep:
$ cat tst.awk NR==1 { fmt="\"%s\";\"%s\"\n"; printf fmt, "Ruta", "Fecha" } sub(/^Ruta: /,"") { ruta=$0 } sub(/^Fecha de último cambio: /,"") { printf fmt, ruta, $0 } $ svn info -R https://SOME_URL/TEST | awk -f tst.awk "Ruta";"Fecha" "TEST";"2016-04-07 15:52:40 -0500 (jue 07 de abr de 2016)" "PRUEBA1.txt";"2016-04-07 15:16:19 -0500 (jue 07 de abr de 2016)" "PRUEBA2.txt";"2016-04-07 15:15:47 -0500 (jue 07 de abr de 2016)"
有很多方法可以很容易地完成。 你可以使用你的shell(任何带有参数扩展和子串删除的现代shell),或者你可以使用sed
或者awk
或者它们的任意组合。
你还没有指定shell,但只要你有一个符合POSIX标准的shell,一个简短的脚本就可以以相当简单的方式处理/解析你的svn命令的结果。 以下使用bash,但参数扩展可以在任何POSIX shell中使用:
#!/bin/bash fname="${1:-/dev/stdin}" ## read from given filename or stdin (default) echo "Ruta;Fecha" ## print heading while read -r line; do ## for each line of input [ "${line%%:*}" = "Ruta" ] && echo -n "${line##* }" ## begins 'Ruta' [ "${line%%:*}" = "Fecha de último cambio" ] && { ## begins "Fecha.." tmp="${line#*:}" echo ";${tmp:1}" } done < "$fname"
输入文件
$ cat dat/ruta.txt Ruta: TEST Fecha de último cambio: 2016-04-07 15:52:40 -0500 (jue 07 de abr de 2016) Ruta: PRUEBA1.txt Fecha de último cambio: 2016-04-07 15:16:19 -0500 (jue 07 de abr de 2016) Ruta: PRUEBA2.txt Fecha de último cambio: 2016-04-07 15:15:47 -0500 (jue 07 de abr de 2016)
使用/输出
$ cat dat/ruta.txt | bash parseruta.sh Ruta;Fecha TEST;2016-04-07 15:52:40 -0500 (jue 07 de abr de 2016) PRUEBA1.txt;2016-04-07 15:16:19 -0500 (jue 07 de abr de 2016) PRUEBA2.txt;2016-04-07 15:15:47 -0500 (jue 07 de abr de 2016)
要使用您的命令(在使用chmod 0755 scriptname
执行脚本之后),您可以执行以下操作:
svn info -R https://SOME_URL/TEST | \ grep 'Ruta: \|Fecha de último cambio: ' | \ scriptname
(这是所有一行上面的行延续'\'
结尾)
试试看,如果你有问题,请告诉我。
如果仅限于一个POSIX shell(或没有以${var:start:end}
形式的字符串索引的shell),那么就有一个需要更改的命令。 POSIX以不同的方式处理字符串索引,所以你需要改变:
echo ";${tmp:1}"
至
echo $(expr substr "$tmp" 2 $(expr length "$tmp"))
以删除"Fecha..."
部分后,从第二个字符开始的子字符串索引。
另一个awk的选择
$ awk -vq='"' 'NR==1{print q "Ruta" q ";" q "Fecha" q} /^Ruta:/{t=q $2 q; next} {sub(/[^:]+: /,""); print t ";" q $0 q}' file "Ruta";"Fecha" "TEST";"2016-04-07 15:52:40 -0500 (jue 07 de abr de 2016)" "PRUEBA1.txt";"2016-04-07 15:16:19 -0500 (jue 07 de abr de 2016)" "PRUEBA2.txt";"2016-04-07 15:15:47 -0500 (jue 07 de abr de 2016)"