更改文本文件中的文本

更改文本文件中的文本

是否有命令行方式来更改文件中的文本?就像我想将所有字符串“lukuunottamatta”更改为“lukuun ottamatta”形式,将“Lukuunottamatta”更改为“Lukuun ottamatta”形式。

答案1

sed 会做你所要求的: http://www.brunolinux.com/02-The_Terminal/Find_and%20Replace_with_Sed.html

例如sed -i 's/lukuunottamatta/lukuun ottamatta/g' /home/user/myfile.txt

需要注意的是,并非所有版本的 sed 都存在 -i 选项(允许您就地更改文件)。如果您使用的是旧版本,则可能需要将更改的版本写入临时文件,然后将临时文件内容复制(或移动)到实际文件中。

这是一个从头到尾执行您所要求的操作的示例:

echo "some stuff" > myfile.txt
echo "some more stuff" >> myfile.txt
echo "lukuunottamatta" >> myfile.txt
echo "and yet some more stuff" >> myfile.txt
sed -i 's/lukuunottamatta/lukuun ottamatta/g' myfile.txt
cat myfile.txt (and view that lukuunottamatta was indeed replaced with lukuun ottamatta)

相关内容