2016-11-28 88 views
2

這sed的comandline腳本預先考慮在一個文件中的每一行文字:添加文字到每個n階行的文本文件

sed -i 's/^/to be prepended/g' text.txt 

我怎樣才能使它所以只做到這一點對每n 線?

我正在使用測序數據,並且在「norma」多個fasta格式中,首先有一個標識符行用>來盯着,然後有額外的文本。

下一行以像「AATTGCC」等隨機DNA序列開始,當該字符串完成其新行和新標識符時,我如何在序列行的開頭添加文本(其他基)?

+1

Fasta格式並不總是交替的標題/序列行,你不應該依賴它!只需使用只有標題行以'>'開頭的事實 –

回答

1
$ seq 10 | perl -pe's/^/to be prepended/unless $. % 3' 
1 
2 
to be prepended 3 
4 
5 
to be prepended 6 
7 
8 
to be prepended 9 
10 
$ seq 10 | perl -pe's/^/to be prepended/unless $. % 3 - 1' 
to be prepended 1 
2 
3 
to be prepended 4 
5 
6 
to be prepended 7 
8 
9 
to be prepended 10 
$ seq 10 | perl -pe's/^/to be prepended/unless $. % 3 - 2' 
1 
to be prepended 2 
3 
4 
to be prepended 5 
6 
7 
to be prepended 8 
9 
10 

你有個想法。

4

只需使用以下GNU sed語法:

sed '0~Ns/^/to be prepended/' 
# ^^^ 
# set N to the number you want! 

例如,在前面加上HA到線數的4,其是多方面的:

$ seq 10 | sed '0~4s/^/HA/' 
1 
2 
3 
HA4 
5 
6 
7 
HA8 
9 
10 

或者到那些形式4N+1上:

$ seq 10 | sed '1~4s/^/HA/' 
HA1 
2 
3 
4 
HA5 
6 
7 
8 
HA9 
10 

來自sed manual → 3.2. Selecting lines with sed

第一〜步驟

這GNU擴展第一起始線上的每個第STEP線相匹配。特別是,當存在一個非負的n時,會選擇行,這樣當前的行號等於first +(n * step)。因此,要選擇奇數行,可以使用1〜2;從第二個開始選擇每第三行,將使用'2〜3';從第十行開始選擇第五行,使用'10〜5';和'50〜0’ 是說50

順便說的只是一個模糊的方式,就沒有必要使用/g全球更換,因爲^只需一次在每一行更換。

0
seq 15|awk -v line=4 'NR%line==0{$0="Prepend this text : " $0}1' 
1 
2 
3 
Prepend this text : 4 
5 
6 
7 
Prepend this text : 8 
9 
10 
11 
Prepend this text : 12 
13 
14 
15 
相關問題