使用通配符替换sed

时间:2012-07-24 15:17:35

标签: unix sed

如何使用sed执行以下替换?

输入

group_0 group_10 n_name_0 n_name_10 n_name_20 n_name_5 n_name_40 team_20 team_1

必需的输出

group_0 group_10 n_name n_name n_name n_name n_name n_name team_20 team_1

我尝试使用sed -i的/ n_name * / n_name / g'但它删除了n_name之后的所有内容

3 个答案:

答案 0 :(得分:1)

sed -i 's:\(n_name\)_[[:digit:]]*:\1:g'

答案 1 :(得分:0)

根据您的输入数据运作:

sed -r 's/_[0-9]+//g'

见下面一行:

kent$   echo "group0 group1 n_name_0 n_name_10 n_name_20 n_name_5 n_name_40 team0 team1"|sed -r 's/_[0-9]+//g'
group0 group1 n_name n_name n_name n_name n_name team0 team1

<强>更新

更新了您的新输入

sed -r 's/(n_name)_[0-9]+/\1/g'

试验:

kent$ echo "group_0 group_10 n_name_0 n_name_10 n_name_20 n_name_5 n_name_40 team_20 team_1"|sed -r 's/(n_name)_[0-9]+/\1/g' 
group_0 group_10 n_name n_name n_name n_name n_name team_20 team_1

<强>更新

我假设您要在shell脚本中使用该行。所以请看下面的测试:

kent$  ls
test.txt

kent$  cat test.txt 
group_0 group_10 n_name_0 n_name_10 n_name_20 n_name_5 n_name_40 team_20 team_1

kent$  commandSed=$(sed -r 's/(n_name)_[0-9]+/\1/g' test.txt > out.txt)

kent$  ls
out.txt  test.txt

kent$  cat out.txt
group_0 group_10 n_name n_name n_name n_name n_name team_20 team_1

实际上commandSed var在这里没有任何意义。

如果你这样做:

kent$  commandSed=$(sed -r 's/(n_name)_[0-9]+/\1/g' test.txt)   

(不重定向到新文件)

kent$  echo $commandSed 
group_0 group_10 n_name n_name n_name n_name n_name team_20 team_1

如果你想在新文件和commandSed变量中输出两个,tee是你的朋友:

kent$  commandSed=$(sed -r 's/(n_name)_[0-9]+/\1/g' test.txt|tee out.txt)  

kent$  echo $commandSed                                                  
group_0 group_10 n_name n_name n_name n_name n_name team_20 team_1

kent$  cat out.txt 
group_0 group_10 n_name n_name n_name n_name n_name team_20 team_1

答案 2 :(得分:0)

对此的解决方案非常简单。在http://www.unix.com/shell-programming-scripting/31583-wildcards-sed.html

上找到了这个
$commandSed ="sed -r 's/n_name_[0-9]*/un_cell/g' test.txt>out.txt";
system($commandSed);