2016-08-10 51 views
2

我有一個文件,我必須迭代幾次,每次都用python運行它。我如何從shell中的特定行刪除或添加字符?如何添加或刪除shell中指定行號的字符?

爲例文件ex.file,

$ cat ex.file 
stuff 
more stuff 
more stuff 
more stuff 
#<- remove this character 
<-add a pund sign here 
more stuff 
more stuff 

我所需的輸出將是:

sed '6 s/^/#/' ex.file 

$ cat ex.file 
stuff 
more stuff 
more stuff 
more stuff 
<- remove this character 
#<-add a pund sign here 
more stuff 
more stuff 

回答

3

爲了在線路6的起動添加#要刪除第5行的前導#:

sed '5 s/^#//' ex.file 
+0

如何將sed指向'ex.file'? – kilojoules

+0

@kilojoules:看我的編輯。您可以使用'sed -i'而不是'sed'來編輯文件,或者您可以將它寫入像sed ...> newfile'這樣的新文件。 –

+0

非常感謝!我怎樣才能覆蓋'ex.file'? – kilojoules

1

Oneliner awk版本從第5行刪除#並將#添加到第6行。

awk 'NR==5 {sub(/^#/,"") } NR==6 { sub(/^/,"#")}1' infile 
相關問題