使用 cut 过滤固定宽度的文件

Using cut to filter a fixed width file

假设我有这样一个文件:

1        10        20        30        40       50
==================================================
foofoofoo1111111111bblah      moreblahblblahblah
foofoofoo2          foofoo              stuffhere

============================================= ====

我想 return 位置 11-20 和 31-40 为空白的所有行。我可以使用 cut:

来识别它们
cut -b 11-20,31-40 < source.txt

那return就是那些位置的字符。

====================
111111111bmoreblahbl

====================

第二行(忽略===行)全是空格。 我想将这些字符为 blank/spaces 的整行(所以这里是第二行)重定向到一个新文件。我不知道如何结合 cut 和 grep 来做到这一点。这当然是可能的,但我无法解决。

是这样的吗?使用 awk:

$ awk 'substr([=10=],11,10) substr([=10=],31,10)~/^ *$/' file
foofoofoo2          foofoo              stuffhere

解释:

$ awk '
substr([=11=],11,10) substr([=11=],31,10)~/^ *$/ # positions 11-20 and 31-40 are all space
' file

使用grep

$ grep "^.\{10\} \{10\}.\{10\} \{10\}" file

从一开始 (^) 有 10 个任意字符 (.\{10\}) 然后是 10 个空格 (\{10\}) 并重复。

编辑:

grep 的更短版本:

$ grep "^\(.\{10\} \{10\}\)\{2\}" file

对于 FIELDWIDTHS 使用 GNU awk:

$ awk -v FIELDWIDTHS='10 10 10 10' '~/^ *$/' file
foofoofoo2          foofoo              stuffhere