如何使用awk获取指定位置任一侧的子字符串

how to use awk to get substring either side of a specified position

我正在使用 awk 获取基于位置变量的子字符串。想象一下:

string = "ABC NGC 2345678."
echo $string | awk '{print substr([=10=],5,8)}'

输出:

"NGC 2345"

这一切都很好,但是如果我想提取位置 5 两边的 8 个字母怎么办?或者更好的是,因为只有 5 个位置存在倒退,我如何概括它以获得一个 "up to 8 positions either side of the position of interest?"

的子字符串

所以输出是

"ABC NGC 2345"

谢谢。

你可以在这里使用 sed。

$ echo "ABC NGC 2345678." | sed 's/^\(.\{4\}..\{0,7\}\).*//'
ABC NGC 2345

我想您可能想要一个通用的解决方案,而不仅仅是为了解决您的示例问题。

看看这个 awk 单行代码:

awk -v i=5 -v o=8 '{d=i-o;s=d>0?d:1;print substr([=10=],s,2*o+(d<0?d:1))}'

您只需更改 i ( interesting position)o (the offset to each side)

我们来做个测试:

kent$  str="54321#123456789"                                                                                                                                                

kent$  awk -v i=6 -v o=3 '{d=i-o;s=d>0?d:1;print substr([=11=],s,2*o+(d<0?d:1))}'<<<$str                                                                                
321#123

kent$  awk -v i=6 -v o=5 '{d=i-o;s=d>0?d:1;print substr([=11=],s,2*o+(d<0?d:1))}'<<<$str                                                                                
54321#12345

kent$  awk -v i=6 -v o=7 '{d=i-o;s=d>0?d:1;print substr([=11=],s,2*o+(d<0?d:1))}'<<<$str                                                                                
54321#1234567

kent$  awk -v i=6 -v o=77 '{d=i-o;s=d>0?d:1;print substr([=11=],s,2*o+(d<0?d:1))}'<<<$str
54321#123456789