Issue
we want to remove the word - -XX:+UseCMSInitiatingOccupancyOnly
from the following file
more hdfs.conf
SHARED_HADOOP_NAMENODE_OPTS="-server -XX:ParallelGCThreads=8 -XX:+UseCMSInitiatingOccupancyOnly -Xms{{namenode_heapsize}}"
so we did the following:
sed -i -E 's/\-XX:\+UseCMSInitiatingOccupancyOnly//g' hdfs.conf
-E enables extended regular expressions (needed for + and grouping). , and I using the "" before the "-" and "+"
Note - appreciate comments comments about my sed syntax and if I missing something
the problem with my sed is that we have one additional space when we delete the word ( according to my sed suggestion )
example of what we get
more hdfs.conf
SHARED_HADOOP_NAMENODE_OPTS="-server -XX:ParallelGCThreads=8 -Xms{{namenode_heapsize}}"
instead to get the line without additional spaces as
more hdfs.conf
SHARED_HADOOP_NAMENODE_OPTS="-server -XX:ParallelGCThreads=8 -Xms{{namenode_heapsize}}"
so how to improve my sed syntax in order to delete also the additional space ?
Solution
The extra spaces shouldn't matter to whatever parses those options later unless it's really badly written code. Assuming that's the case and an extra space causes an error...
As always, if you want to edit a file in a script and your first inclination is to turn to sed -i
, I suggest using ed
instead. Unlike sed
's -i
option, it's standardized and behaves the same everywhere, meaning you're less likely to run into unwelcome surprises when running in different environments. You can adjust the following regular expression to work with sed
if really desired, though:
ed -s hdfs.conf <<'EOF'
/^SHARED_HADOOP_NAMENODE_OPTS=/ s/\( *\)-XX:+UseCMSInitiatingOccupancyOnly */\1/
w
EOF
The trick here is to also match 0 or more preceding and following spaces, but only leave one of the two (The first in this case) present in the output.
This also only tries to substitute on the line setting the particular variable whose contents you're interested in, in case the option you're removing appears elsewhere (In a comment, say) and you want to keep that occurrence.
And since this is tagged perl, a perl
version:
perl -pi -e 's/\s*\K\Q-XX:+UseCMSInitiatingOccupancyOnly\E\s*// if /^SHARED_HADOOP_NAMENODE_OPTS/' hdfs.conf
(Stuff inside \Q
... \E
is treated literally so the +
doesn't need to be escaped, and \K
basically discards what matches before it from the final matched text, meaning you don't need the explicit capture group of the leading whitespace characters (Which \s
matches instead of a literal space))
Answered By - Shawn Answer Checked By - Terry (WPSolving Volunteer)