Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 使用Linux sed正则表达式替换文本文件中的Windows文件路径_Regex_Linux_Windows_Parsing_Sed - Fatal编程技术网

Regex 使用Linux sed正则表达式替换文本文件中的Windows文件路径

Regex 使用Linux sed正则表达式替换文本文件中的Windows文件路径,regex,linux,windows,parsing,sed,Regex,Linux,Windows,Parsing,Sed,我有大量带有标签式语法的文本文件。这些文件包含如下模式: <TAG1=foo><TAG-2=\\10.0.0.1\directory\filename.pdf><TAG3> ... <TAG4=bar><TAG-6=\\10.0.0.1\directory\filename.tif,other content><TAG5> 。。。 我需要用新路径替换这些UNC路径的第一部分,这意味着: <TAG1=foo>&

我有大量带有标签式语法的文本文件。这些文件包含如下模式:

<TAG1=foo><TAG-2=\\10.0.0.1\directory\filename.pdf><TAG3> ...
<TAG4=bar><TAG-6=\\10.0.0.1\directory\filename.tif,other content><TAG5>
。。。
我需要用新路径替换这些UNC路径的第一部分,这意味着:

<TAG1=foo><TAG-2=D:\localdirectory\filename.pdf><TAG3> ...
<TAG4=bar><TAG-6=D:\localdirectory\filename.tif,other content><TAG7>
。。。
有大量的文件要处理,所以我需要自动进行路径替换。到目前为止,我使用sed(在Linux上)尝试了多个regex,但没有找到解决方案

#!/bin/bash

# New directory (escaped)
newpath='D:\\localdirectory\\'
# Actual replacement (don't work)
sed -i "s@\(<TAG-2=\)\([^\\]+\.pdf\)@\1${newpath}\2@g" filetoprocess.txt 
sed -i "s@\(<TAG-6=\)\([^\\]+\.tif\)@\1${newpath}\2@g" filetoprocess.txt 
#/bin/bash
#新目录(转义)
newpath='D:\\localdirectory\\'
#实际更换(不工作)

sed-i“s@\(此使用sed的shell脚本可能会工作:

#!/bin/bash

oldpath='\\\\10\.0\.0\.1\\directory\\'
newpath='D:\\localdirectory\\'

#sed -i "s@${oldpath}@${newpath}@g" filetoprocess.txt
sed  -r -i "s@(<TAG-2=)${oldpath}([^>]+pdf)@\1${newpath}\2@g;
         s@(<TAG-6=)${oldpath}([^>]+tif)@\1${newpath}\2@g;
       " filetoprocess.txt
!/bin/bash
oldpath='\\\10\.0\.0\.1\\directory\\'
newpath='D:\\localdirectory\\'
#sed-i“s@${oldpath}@${newpath}@g”filetoprocess.txt
sed-r-i“s@(]+pdf)@\1${newpath}\2@g;
s@(]+tif)@\1${newpath}\2@g;
“filetoprocess.txt
在第一行中,shell shebang是
#!
(注意感叹号)。我相信输入示例中的第二行应该有标记-6

在路径中,需要注意正则表达式中具有特殊含义的字符:

  • 您必须用反斜杠转义
    \
  • 这导致了看起来很滑稽的
    \\\\
    (两个转义的反斜杠)
在最后一行中,
-r
选项在参数中节省了一点转义。请注意,我使用了
[^>]+
而不是
[^\\]+
来获取扩展之前的路径部分

  • sed命令中的
    [^\\]+
    将匹配
    =
    之后的所有内容,该部分不是
    \
    ,只是
    D:
    部分
  • 因此,您的替换将只匹配文本
    D:.pdf
但我建议尝试使用另一个(注释)sed命令,它只替换路径,而不管标记和文件扩展名是什么


(以前备份过您的文件,因为您使用了
-i
就地替换。)

最后,我提供了以下正则表达式。此解决方案还可以管理“/”Unix路径、美元($)和连字符(-):


sed-i-r's@“Lars Fischer"当然,“OLDDPATH”在我需要修改的成千上万个文件中是不一致的。
newpath
是前缀。
([^>]+pdf)
应该匹配前缀后面的以下路径部分,包括文件名和扩展名(
.pdf
)。
sed -i -r 's@(<TAG-2=|TAG-6=)([\/]{2})([0-9.a-zA-Z_$ -]+[\/])+([0-9.a-zA-Z_$ -]+\.[pPtT][dDiI][fF])@\1'"${newpath}"'\\\4@g'