本文介绍了Linux sed命令-在反斜杠中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试替换文件中的字符串.我必须使用变量,因为我必须在很多行中执行此操作.我如何逃避反斜杠?
I'm trying to replace a string in a file. i have to use a variable since i have to do this in alot of lines. how do i escape the backslash?
text.txt:
1234567#Hello World#Hello I\u0027m Scott
脚本:
#!/bin/bash
FOLDERID=`cat text.txt | cut -d# -f1` # example: 12345
oldstring=`cat text.txt | cut -d# -f2` # example: "Hello World"
newstring=`cat text.txt | cut -d# -f3` # example: "Hello I\u0027m Scott"
sed -i "s/${oldstring}/${newstring}/g" $FOLDERID/myfile.txt
sed后
cat myfile.txt
cat myfile.txt after sed
Hello I0027m Scott
我怎样才能逃脱反斜线?我只知道如何转义像这样的斜杠:
how can i escape a backslash? i only know how to escape slashes which would work like:
newstring=Hello I/u0027m Scott
newstring=${newstring//\//\\\/}
echo ${newstring} # => Hello I\/u0027m Scott
推荐答案
尝试一下:
cd /tmp
mkdir -p 1234567
echo Hello World >1234567/myfile.txt
echo '1234567#Hello World#Hello I\u0027m Scott' >text.txt
那么,然后:
IFS=\# read -r FOLDERID oldstring newstring <text.txt
sed "s/${oldstring}/${newstring//\\/\\\\}/g" -i $FOLDERID/myfile.txt
cat 1234567/myfile.txt
Hello I\u0027m Scott
这篇关于Linux sed命令-在反斜杠中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!