如何用 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 's/n_name*/n_name/g' 但它会删除 n_name 之后的所有内容
sed -i 's:\(n_name\)_[[:digit:]]*:\1:g'
解决方案非常简单。在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);
根据您的输入数据工作:
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