这
可以用awk,sed或PHP来完成。我有逗号分隔的字符串,我想删除一个值。
mike,suzy,carter,jason
$remove_value = mike
sed 's/$remove_value//' file_with_delimited_string
这给了我",苏西,卡特,杰森">
$remove_value = jason
sed 's/$remove_value//' file_with_delimited_string
这给了我"迈克,苏西,卡特">
如何删除错误的逗号,无论删除的值的位置如何?这是一个包含许多逗号分隔字符串的大文件。此更改必须仅适用于当前匹配项。我正在使用PHP在Linux服务器上编辑文本文件。
你可以试试这个简单的方法
sed "s/,'?$remove_value,'?//" FileName
如果你测试中间值,你可以这样使用
sed "s/,$remove_value'|$remove_value,//" FileName
如果删除行中出现的所有值,请使用g
sed "s/,$remove_value'|$remove_value,//g" FileName
例:
remove_value='mike'
输出:
suzy,carter,jason
例:
remove_value='suzy'
输出:
mike,carter,jason
例:
remove_value='jason'
输出:
mike,suzy,carter
sed -r "s/$remove_value,?//g; s/,$//" File
这将解决问题。
$remove_value = ltrim($remove_value, ',');
$remove_value = rtrim($remove_value, ',');
这里有一个古怪的方法在php中做到这一点:
$list = 'mike,suzy,carter,jason';
$list_array = explode(',' , $list);
$goner = 'suzy';
$goner_index = array_search($goner, $list_array);
unset($list_array[$goner_index]);
$list = implode(',', $list_array);
在 php 中通过单个正则表达式。
$str = "jason,mike,jason,suzy,carter,jason";
$remove_value = "jason";
echo preg_replace('~,'.$remove_value.'(?=,|$)|^'.$remove_value.',~', "", $str);
输出:
mike,suzy,carter
with awk:
$ for replace_string in mike suzy carter jason;
do awk -v s=$replace_string '{ sub("((,|^)"s")|("s"(,|$))","") }1' a.txt;
done
suzy,carter,jason
mike,carter,jason
mike,suzy,jason
mike,suzy,carter