2015-09-01 79 views
2

嗨只需要在文件的第n行在第n行替換的字符串的文件

文件1

hi this is line 1 
    hi this is line 2 
    hi this is line 3 
    hi this is line 4 

我只需要在第2行替換「喜」替換文件字符串

experted如下

hi this is line 1 
    Hello this is line 2 
    hi this is line 3 
    hi this is line 4 

我試圖通過創建一個臨時文件

sed -n 2p file1 > temp1 
    perl -pi -e 's/hi/Hello/g' temp1 \\I tried to replace temp1 with line 2 in file1 
    sed -i '2d' file1 \\after this I failed to insert temp1 as a 2nd line in file1 

幫助我在第N行替換文件中的字符串(沒有臨時文件是首選..)。

謝謝

+0

如果你已經可以使用perl,那麼我會建議:'my $ i = 0; while(<>){$ i ++; if($ i == 2){s/^ hi/Hello /}; print;}' – flaschenpost

回答

7

這可能會爲你工作:

sed -i '2s/hi/Hello/' file 
+0

謝謝你的工作正常。 – Ravichandra

0

上面的回答是正確的,但我很想把AWK變種僅供參考。

awk 'NR==2{gsub("hi","Hello",$1)}; {print $0}' file > newfile 
相關問題