Monday 15 March 2010

bash - sed regex is replacing an entire file -



bash - sed regex is replacing an entire file -

i have hdfs-site.xml file contains next information

<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <!-- set site-specific property overrides in file. --> <configuration> <property> <name>dfs.replication</name> <value>3</value> </property> <property> <name>dfs.name.dir</name> <value>/data/dfs/nn</value> </property> <property> <name>dfs.data.dir</name> <value>/data/dfs/dn,/mnt_test_volume/data/dfs/dn,/mnt_test_volume/data/dfs/dni,/mnt_test_v5olume/data/dfs/dn,/mnt_test_volume/d5ata/dfs/dgn</value> </property> <property> <name>dfs.permissions</name> <value>false</value> </property> </configuration>

i want remove of entries nowadays in <name>dfs.data.dir</name><value> , </value></name> tags. entry remove decided 1 parameter shell script.

i new sed , have written next sed command find particular entry , delete it. works expected when sed executed first time when same command executed next time, contents of file wiped out , file becomes blank file.

sed -ni '1h; 1!h; ${g; s#\(<name>dfs\.data\.dir<\/name>[^a-za-z0-9]*<value>.*\)'$data_dir_path'[^,<]\(.*<\/value>\)#\1\2# p}' hdfs-site.xml

in command $data_dir_path variable decides entry deleted.

for example, if value of data_dir_path /mnt_test_volume/data/dfs/dn expecting next output

<name>dfs.data.dir</name> <value>/data/dfs/dn,,/mnt_test_volume/data/dfs/dni,/mnt_test_v5olume/data/dfs/dn,/mnt_test_volume/d5ata/dfs/dgn</value>

which working fine when command executed 1 time if same command executed next time, entire file becomes empty.

can please tell me doing wrong here?

you can utilize much simpler sed as

sed "/<name>dfs.data.dir<\/name>/ {n; s#$data_dir_path##}" hdfs-site.xml

what does?

-i inplace editing of file

'/<name>dfs.data.dir<\/name>/ checks if line matches pattern. if yes commands next excecuted. note commands next grouped in {} {n; s/'$data_dir_path'//}'

n; reads next line file pattern space

s/'$data_dir_path'// substiture value in $data_dir_path null

test

$ sed "/<name>dfs.data.dir<\/name>/ {n; s#$data_dir_path##}" test bash-3.2$ cat test : : : <name>dfs.data.dir</name> <value>/data/dfs/dn,,i,/mnt_test_v5olume/data/dfs/dn,/mnt_test_volume/d5ata/dfs/dgn</value> : : :

regex bash shell sed

No comments:

Post a Comment