经过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

相关文章
相关标签/搜索