經過Bash命令在文本文件中查找和替換

查找和替換給定輸入字符串(例如abc )並替換爲另外一個字符串(例如文件/tmp/file.txt XYZ的最簡單方法是什麼? php

我正在編寫一個應用程序,並使用IronPython經過SSH執行命令-但我不太瞭解Unix,也不知道要尋找什麼。 html

我據說Bash除了是命令行界面以外,還能夠是一種很是強大的腳本語言。 所以,若是這是真的,我假設您能夠執行相似的操做。 mysql

我能夠用bash作到嗎,實現個人目標最簡單的腳本(一行)是什麼? linux


#1樓

找到了這個線程,我贊成它包含最完整的答案,因此我也添加了個人: sql

1)sed和ed很是有用...用手! 從@Johnny看下面的代碼: shell

sed -i -e 's/abc/XYZ/g' /tmp/file.txt

2)當個人限制是要經過shell腳本使用它時,不能在內部使用任何變量代替abc或XYZ! 彷佛至少符合個人理解。 所以,我不能使用: vim

x='abc'
y='XYZ'
sed -i -e 's/$x/$y/g' /tmp/file.txt
#or,
sed -i -e "s/$x/$y/g" /tmp/file.txt

可是,咱們該怎麼辦? 由於,@ Johnny說使用「讀的時候...」,可是不幸的是,這還不是故事的結局。 如下內容對我來講效果很好: bash

#edit user's virtual domain
result=
#if nullglob is set then, unset it temporarily
is_nullglob=$( shopt -s | egrep -i '*nullglob' )
if [[ is_nullglob ]]; then
   shopt -u nullglob
fi
while IFS= read -r line; do
   line="${line//'<servername>'/$server}"
   line="${line//'<serveralias>'/$alias}"
   line="${line//'<user>'/$user}"
   line="${line//'<group>'/$group}"
   result="$result""$line"'\n'
done < $tmp
echo -e $result > $tmp
#if nullglob was set then, re-enable it
if [[ is_nullglob ]]; then
   shopt -s nullglob
fi
#move user's virtual domain to Apache 2 domain directory
......

3)正如能夠看到是否設置了nullglob的狀況,當存在一個包含*的字符串時,它的行爲很奇怪 dom

<VirtualHost *:80>
 ServerName www.example.com

變成 編輯器

<VirtualHost ServerName www.example.com

沒有結尾尖括號,Apache2甚至沒法加載!

4)這種解析應該比一鍵搜索和替換要慢,可是,正如您已經看到的,對於4個不一樣的搜索模式,有4個變量在一個解析週期內起做用!

在給定的問題假設下,我能想到的最合適的解決方案。


#2樓

我很驚訝,由於我偶然發現了這個...

軟件包「 mysql-server」附帶了一個「 replace」命令,所以,若是已安裝,請嘗試一下:

# replace string abc to XYZ in files
replace "abc" "XYZ" -- file.txt file2.txt file3.txt

# or pipe an echo to replace
echo "abcdef" |replace "abc" "XYZ"

看到男人替換更多關於這個...


#3樓

您可使用rpl命令。 例如,您想在整個php項目中更改域名。

rpl -ivRpd -x'.php' 'old.domain.name' 'new.domain.name' ./path_to_your_project_folder/

緣由尚不清楚,但這是很是快速和有用的。 :)


#4樓

要非交互地編輯文件中的文本,您須要就地文本編輯器,例如vim。

這是如何從命令行使用它的簡單示例:

vim -esnc '%s/foo/bar/g|:wq' file.txt

這至關於編輯器的@slim答案 ,基本上是同一回事。

這裏有幾個ex的實際例子。

用文件中的bar替換文本foo

ex -s +%s/foo/bar/ge -cwq file.txt

刪除多個文件的尾隨空格:

ex +'bufdo!%s/\s\+$//e' -cxa *.txt

故障排除(端子卡住時):

  • 添加-V1參數以顯示詳細消息。
  • 強制退出者: -cwq!

也能夠看看:


#5樓

若是將URL替換爲「 /」字符,請當心。

如何執行此操做的示例:

sed -i "s%http://domain.com%http://www.domain.com/folder/%g" "test.txt"

摘自: http : //www.sysadmit.com/2015/07/linux-reemplazar-texto-en-archivos-con-sed.html

相關文章
相關標籤/搜索