Friday, March 29, 2013

bash: як замінити стрічку у файлі

маємо файл file.txt

# cat file.txt
this is simple text file
here is 1-st line
4-th line
some 3-rd line
end of file



Наприклад, треба замінити стрічку яка містить  "4-th line" . Зробити це можна за допомогою sed-у:


# cat file.txt | sed '/4-th line/c 2-nd line'
this is simple text file
here is 1-st line
2-nd line
some 3-rd line
end of file



Але треба памятати, що sed міняє сам файл у такому випадку. Тому, якщо треба змнити файл, можна зробити шось таке:


# cat file.txt | sed '/4-th line/c 2-nd line' > tmp.txt && mv tmp.txt file.txt


таким вийшов  новий файл


# cat file.txt
this is simple text file
here is 1-st line
2-nd line
some 3-rd line
end of file






No comments: