简体   繁体   中英

perl or sed command to find 2 strings and replace the first string with string 2

I have multiple files with below text.

Content of File 1:

Begin("tmp1","derived from file \"/disks/setup/ORIG_FILE1.txt\"");

Content of File 2:

Begin("tmp1","derived from file \"/disks/setup/ORIG_FILE2.txt\"");

Content of File 3:

Begin("tmp9","derived from file \"/disks/setup/ORIG_FILE4.txt\"");

and so on.....

Is there any command in perl or sed to find a line with "Begin" and in that line search from the first string between "..." (ie "tmp1" in our case) and store it in a variable then search for the last string between /..\\"" ie (ORIG_FILE1.txt here) and store it in the variable 2 and then remove ".txt" from the variable 2 and then replace variable 1 with variable 2 and update the file.

So output files will look like:

Content of File 1:

Begin("ORIG_FILE1","derived from file \"/disks/setup/ORIG_FILE1.txt\"");

Content of File 2:

Begin("ORIG_FILE2","derived from file \"/disks/setup/ORIG_FILE2.txt\"");

Content of File 3:

Begin("ORIG_FILE4","derived from file \"/disks/setup/ORIG_FILE4.txt\"");

and so on.....

Can somebody please help me here?

Try this:

perl -i.bak -pe '
    if (/.*\/(.+)\.txt/) {
        $file = $1;
        s/(?<=").*?(?=")/$file/
    }
' file1 file2 file3 ...

That will first capture the "orig" file name (assuming they all have ".txt" extension), then replace the "tmp" placeholder.

With any sed in any shell on any UNIX box:

$ sed 's/\([^"]*"\)[^"]*\(.*\/\([^.]*\)\)/\1\3\2/' file
Begin("ORIG_FILE1","derived from file \"/disks/setup/ORIG_FILE1.txt\"");
Begin("ORIG_FILE2","derived from file \"/disks/setup/ORIG_FILE2.txt\"");
Begin("ORIG_FILE4","derived from file \"/disks/setup/ORIG_FILE4.txt\"");

通过gnu sed作为您在“ d”中的数据,

 sed -E 's~^(Begin\(")\w+(".+/)(\w+)(\.\w+\\""\);)~\1\3\2\3\4~' d

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM