![](/img/trans.png)
[英]How to delete first two lines and last four lines from a text file with bash?
[英]How to pull data from only the first and last lines of a text file
我有一个运行时间很长的程序,my_prog有一些我要解析的输出,以获得两个变量,$ start和$ end。 这是输出的样子:
Important data between the first set of pipes|3|a| This line is not interesting to me|5|c| ... Another line with data (at the end this time)|4|b|
在上面的例子中,我只需要:
start=3 end=b
我在bash脚本中使用它。 我有一种感觉awk可以完全解决这个问题,但是做一个start=$(my_prog|awk ...)
将只给出一个变量。 我想我可以做一个my_array=($(my_prog|awk ...))
,但这看起来很乱。 另外,我不想将my_prog的(可能很长的)输出放入变量中。 获取数据的好方法是什么? 可以用某种方式直接写入bash变量吗?
因为@Zack写的awk脚本没问题,唯一的改进可能是:
read start end < <(my_prog |
awk -F\| 'NR==1 { start=$2 } END { print start " " $3 }')
我就是这样做的(完全未经测试):
startend=$(my_prog |
awk -F\| 'NR==1 { start=$2 } { end=$3 } END { print start "|" end }')
start=${startend%|*}
end=${startend#*|}
没有必要在文件的每一行上进行分配。 最后一条记录在END
子句中可用,因此您甚至不需要在那里进行分配。
此外,AWK保持单独的OFS(输出字段分隔符),因此您可以在打印时使用输出变量之间的逗号。
delim=" " # or choose one that suits you
read -r -d "$delim" start end < <(my_prog |
awk -F\| -v OFS="$delim" 'NR==1 { start=$2 } END { print start, $3 }')
或者,您可以使用here字符串或此处doc来代替进程替换< <()
:
read ... <<< $(my_prog ...)
要么
read ... <<EOF
$(my_prog ...)
EOF
要完成读取任务,可以将my_prog / awk管道放在一个函数中:
foo () { my_prog | awk ... ; }
read ... < <(foo) # or one of the other redirection methods
也可以eval: eval `myprog | awk -F\\| 'NR==1 { start=$2 } { end=$3 } END { print "start="start " end="end }'`
eval `myprog | awk -F\\| 'NR==1 { start=$2 } { end=$3 } END { print "start="start " end="end }'`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.