
我有一個這樣的文件:
OV2 OVI 1VI OV3 3VI
er 23 23 23 23 23
tr 24 24 24 24 24
我想列印第一列以及名稱包含的任何列VI
(我事先不知道哪些列將包含該字串)。在上面的例子中,輸出應該是這樣的:
OVI 1VI 3VI
er 23 23 23
tr 24 24 24
所有列都應以製表符分隔。
答案1
perl -lane '$,="\t";
$. == 1 and @A = grep $F[$_] =~ /VI/, 0..$#F;
print @F[0,@A];
' yourfile
結果
ID OVI 1VI 3VI
er 23 23 23
tr 24 24 24
在職的
- 從第一行中,
$. == 1
提取包含字串 的欄位的索引VI
。 - 有了 array 中現在的這些索引列表
@A
,我們只需繼續@A
從數組中切出第一個字段+數組中列出的字段即可@F
。已OFS=$,
設定為TAB
. YMMV。
awk
awk -v OFS="\t" '
NR==1{
for ( i=2; i<=NF; i++ )
if ( $i ~ /VI/ )
str = str OFS i
N = split(str, A, OFS)
}{
s = $1
for ( i=2; i<=N; i++ )
s = s OFS $(A[i])
$0 = s
}1
' yourfile
SED
sed -e '
# TAB->spc, multiple spc -> single spc, trim leading/trailing spc
y/ / /;s/[ ]\{2,\}/ /g;s/^[ ][ ]*//;s/[ ][ ]*$//
# only for first line, remove the first field and store remaining in hold area
1{
h
s/[ ]/\
/
s/.*\n//
x
}
# append hold area (which now has 2nd...last fields
# data of the first record) to the present line and
# place a marker at the end of the first field
G
s/[^ ][^ ]*[ ]/&\
/
# setup a do-while loop which progressively either keeps VI data or trims it
:loop
# 1 2 3
s/\(\n\)\([^ ][^ ]*\)[ ]\{0,1\}\(.*\n\)[^ ]*VI[^ ]*[ ]\{0,1\}/ \2\1\3/;tloop
s/\(\n\)[^ ][^ ]*[ ]\{0,1\}\(.*\n\)[^ ][^ ]*[ ]\{0,1\}/\1\2/
/\n\n$/!bloop
# loop ends when the two \ns collide at the end of line
# remove the two \ns and what remains is what you wanted
s///
' yourfile
答案2
awk解決方案:
awk 'BEGIN{FS="[\t ]+"; OFS="\t"}NR==1{for(i=2;i<=NF;i++)
{if($i~/VI/) a[i]; }}{r=$1; for(i in a) r=r OFS $i; print l}' file
輸出:
OVI 1VI 3VI
er 23 23 23
tr 24 24 24
FS="[\t ]+"
- 輸入欄位分隔符OFS="\t"
- 輸出欄位分隔符NR==1
- 為了第一標頭線if($i~/VI/) a[i]
- 捕獲欄位編號(如果符合)VI
r=$1; for(i in a) r=r OFS $i; print r
- 迭代所需的欄位編號並列印它們各自的值
如果遇到順序破壞,請使用以下 withasorti()
函數(按索引對數組進行排序):
awk 'BEGIN{FS="[\t ]+"; OFS="\t"}NR==1{for(i=2;i<=NF;i++)
{if($i~/VI/) a[i]; }}{r=$1; asorti(a,b); for(i in b) {r=r OFS $(b[i])} print r}' file
答案3
Python腳本解決方案。在解析第一行並建立列列表的基礎上進行操作。那些沒有 VI 的列被設定為「無」。所有其他行都被拆分為單字並與列列表項目成對連接以進行比較。如果對應的列項為 None,則不會列印目前行的該單字。否則,將列印非 None 的內容
#!/usr/bin/env python3
import sys
with open(sys.argv[1]) as fd:
indexes = []
for index,line in enumerate(fd):
if index == 0:
columns = line.strip().split()
for i,col in enumerate(columns):
if 'VI' in col or i == 0:
indexes.append(col)
else:
indexes.append(None)
for x in indexes:
if x:
print(x,end=" ")
print("")
continue
for j in zip(line.strip().split(),indexes):
if j[1]:
print(j[0],end=" ")
print("")
注意:替換end=" "
為end="\t"
以獲得製表符分隔的輸出
測試運行:
$ ./get_colums.py input.txt
ID OVI 1VI 3VI
er 23 23 23
tr 24 24 24