[英]Converting SED command to linux command
我有一個 sed 命令,它應該在 linux 上的 python 代碼中運行(使用 os.system() )或轉換為 Z6523EEEB439A3BDD5 代碼。 但我不知道這個 sed 命令到底是做什么的。 如果您給我代碼或幫助我如何在 python 中使用 os.system 實現它,我們將不勝感激,因為我在使用 os.system 時遇到了很多錯誤。
sed -n '1~4s/^@/>/p;2~4p' file1.fastq > file1.fasta
順便說一句,輸入和 output 文件應該在我的 python 代碼中動態定義:
seq_file1 = '6448.fastq'
input_file1 = os.path.join(sys.path[0],seq_file1)
os.system(os.path.join("sed -n '1~4s/^@/>/p;2~4p' "+ seq_file1 + ' > ' + os.path.splitext(os.path.basename(input_file1))[0]+".fasta") , shell = True)
此sed
命令在此文件中同時運行兩個不同的操作。
-n
: 抑制整個文件的 output。 僅打印應用指令p
的行。
1~4
:從第 1 行開始,每 4 行應用下一條指令。
s/^@/>/p
:用>
替換每個前導@
並打印結果。 由於上述指令,這個指令從第 1 行開始每 4 行應用一次。
;
操作分隔符。
2~4
:從第 2 行開始每 4 行應用下一條指令。
p
:打印一行。
這意味着什么:“在從 #1 開始的每 4 行中用>
替換前導@
並從 #2 開始每 4 行打印一次”
file1.fastq
的內容:
@ line 1
@ line 2
@ line 3
@ line 4
@ line 5
@ line 6
@ line 7
@ line 8
@ line 9
@ line 10
@ line 11
@ line 12
運行sed -n '1~4s/^@/>/p;2~4p' file1.fastq > file1.fasta
file1.fasta
的內容
> line 1
@ line 2
> line 5
@ line 6
> line 9
@ line 10
一個很好的參考是: http://www.gnu.org/software/sed/manual/sed.html
以下代碼片段旨在進行教學,因此我避免使用許多 Python 語言資源,可以應用這些資源來改進算法。
我測試了幾次,它對我有用。
# import Regular Expressions module
import re
output = []
# Open the input file in read mode
with open('file1.fastq', 'r') as file_in:
replace_step = 1 # replacement starts in line #1
print_step = 0 # print function starts in line #2 so it bypass one step
for i, line in enumerate(file_in):
if replace_step == 1:
output.append(re.sub('^@', '>', line))
if replace_step >= 4:
replace_step = 1
else:
replace_step += 1
if print_step == 1:
output.append(line)
if print_step >= 4:
print_step = 1
else:
print_step +=1
print("".join(output))
# Open the output file in write mode
with open('file1.fasta', 'w') as file_out:
file_out.write("".join(output))
您還可以使用subprocess.run
:
import subprocess
seq_file_in = '6448.fastq'
seq_file_out = '6448_out.fastq'
with open(seq_file_out, 'w') as fw:
subprocess.run(["sed", r"1~4s/^@/>/p;2~4p", seq_file_in], stdout=fw)
在這種情況下,當sed
命令如此簡短時, subprocess.run
可能會變得非常方便。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.