如何在条件下复制同一文件中的字符串?
我有很多这样的文件:
<?php
/**
* Message.
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
return [
'To copy' => '',
'No to copy' => 'Not to copy as already filed',
];
我想以递归的方式浏览文件夹中的所有文件,搜索空的字符串(请参阅&#34;要复制&#34; 示例),然后从中复制文本在''
内从左到右,如果这个是空的。
在示例中,第一行应该被复制,因为右''
是空的,而不是第二行,因为右''
已经填充(由相同的内容或不相同)。
所以它变成了:
<?php
/**
* Message.
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
return [
'To copy' => 'To copy',
'No to copy' => 'Not to copy as already filed',
];
希望我很清楚。我知道如何在文件中sed
,find
和replace
,但这是我第一次遇到这个具体案例。
感谢您的帮助。
答案 0 :(得分:0)
bash + sed approach:
Creating replace_empty.sh
(test name) bash script:
#!/bin/bash
for f in /tmp/test/*.php
do
sed -i -E "s/^([[:space:]]*)('[^']+') => '[[:space:]]*',\$/\1\2 => \2,/g" $f
done
Replace file path /tmp/test/*.php
with your actual path
sed options:
-i
- to modify file in place
-E
- to allow extended regular expressions
('[^']+')
- captures key name
\1
and \2
- point to the 1st and 2nd captured group respectively
Usage:
bash replace_empty.sh