Santosh Pillai
Santosh Pillai

Reputation: 1391

sed replace using wildcard

How can I carry out the replace below with sed?

input

group_0 group_10 n_name_0 n_name_10 n_name_20 n_name_5 n_name_40 team_20 team_1

required output

group_0 group_10 n_name n_name n_name n_name n_name n_name team_20 team_1

I tried using sed -i 's/n_name*/n_name/g' but it deletes everything after n_name

Upvotes: 0

Views: 9183

Answers (3)

Santosh Pillai
Santosh Pillai

Reputation: 1391

The solution to this was quite simple. Found this on 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);

Upvotes: 0

Kent
Kent

Reputation: 195179

works based on your input data:

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

see the line below:

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

update

updated for your new input

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

test:

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

update

i assume that you want to use that line in your shell script. so see the test below:

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

in fact the commandSed var doesn't make any sense here.

if you do:

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

(without redirecting to new file)

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

if you want to have the output both in new file and commandSed variable, tee is your friend:

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

Upvotes: 0

alinsoar
alinsoar

Reputation: 15803

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

Upvotes: 1

Related Questions