bash删除线条件 [英] bash delete line condition

查看:156
本文介绍了bash删除线条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到解决方案,使用bash有条件地删除文件中的一行。该文件包含字符串中的年份日期,只有当年份低于参考值时,才应删除相应的行。



该文件如下所示:

 'zg_Amon_MPI-ESM -LR_historical_r1i1p1_196001-196912.nc''MD5'
'zg_Amon_MPI-ESM-LR_historical_r1i1p1_197001-197912.nc''MD5'
'zg_Amon_MPI-ESM-LR_historical_r1i1p1_198001-198912.nc''MD5'
'zg_Amon_MPI-ESM-LR_historical_r1i1p1_199001-199912.nc''MD5'
'zg_Amon_MPI-ESM-LR_historical_r1i1p1_200001-200512.nc''MD5'

我想从第1行中获得1969年并将其与参考(比方说1980)进行比较,如果年份低于参考值,则删除整行。这意味着在这种情况下,代码应该删除该文件的前两行。



我尝试过使用sed和grep,但是无法正常工作。



感谢您提出任何建议。 您可以使用 awk

  awk -F-'$ 4> 198000 {print}'文件名

这将输出第二个日期晚于31 / 1979分之12。这不会原地编辑文件,您必须将输出保存到另一个文件,然后将其替换为原始文件:

  awk -F-'$ 4> 198000 {print}'文件名> tmp&& mv tmp文件名

使用 sed 就地):

  sed -i'/.*19[0-7][0-9]..\\ \\.nc / d'文件名

这需要多一点思考,因为您需要构建一个正则表达式来匹配你不想显示的任何值。


I couldn't find a solution to conditionally delete a line in a file using bash. The file contains year dates within strings and the corresponding line should be deleted only if the year is lower than a reference value.

The file looks like the following:

'zg_Amon_MPI-ESM-LR_historical_r1i1p1_196001-196912.nc' 'MD5'
'zg_Amon_MPI-ESM-LR_historical_r1i1p1_197001-197912.nc' 'MD5'
'zg_Amon_MPI-ESM-LR_historical_r1i1p1_198001-198912.nc' 'MD5'
'zg_Amon_MPI-ESM-LR_historical_r1i1p1_199001-199912.nc' 'MD5' 
'zg_Amon_MPI-ESM-LR_historical_r1i1p1_200001-200512.nc' 'MD5'

I want to get the year 1969 from line 1 and compare it to a reference (let's say 1980) and delete the whole line if the year is lower than the reference. This means in this case the code should remove the first two lines of the file.

I tried with sed and grep, but couldn't get it working.

Thanks in advance for any ideas.

解决方案

You can use awk:

awk -F- '$4 > 198000 {print}' filename

This will output all the lines where the second date is later than 31/12/1979. This will not edit the file in-place, you would have to save the output to another file then move that in place of the original:

awk -F- '$4 > 198000 {print}' filename > tmp && mv tmp filename

Using sed (will edit in-place):

sed -i '/.*19[0-7][0-9]..\.nc/d' filename

This requires a little more thought, in that you will need to construct a regex to match any values which you don't want to be displayed.

这篇关于bash删除线条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆