Reputation: 109
The original string is (according to my format)
"cf foo -J 12345 -z -macro TEST_IFDEFINE -macro THIS -macro THIS1 -macro THIS2"
In order to pass it to another script, I am trying to modify it into
"cf foo -J 12345 -z"
To achieve this I have written shell script as follows:
string="cf foo -J 12345 -z -macro TEST_IFDEFINE -macro THIS -macro THIS1 -macro THIS2"
done=0
config="-cf"
name=""
for name in $string
do
if [ $done -eq 1 ];then
string=`echo $string | sed s/"-macro"//g`
string=`echo $string | sed s/"$name"//g`
echo "----->name: $name"
macro_name="$macro_name -d $name"
done=0
echo "----->string: $string"
fi
if [ "$name" = "-macro" ];then
done=1
macro_def=1
fi
done
From this code I am getting output is :
cf foo -J 12345 -z 1 2
Here, $name contains THIS1 and THIS2. But in script when I do
| sed s/"$name"//g`
it removes only
'THIS'
But keeping
1 2
along with original string. This means script is discarding only alphabets not numeric values in $name. Suggest me something to achieve this.
Upvotes: 1
Views: 3300
Reputation: 532418
With extended patterns enabled, you can use a single parameter expansion.
$ shopt -s extglob
$ foo="cf foo -J 12345 -z -macro TEST_IFDEFINE -macro THIS keepme -macro THIS1 -macro THIS2 keepme"
$ echo "${foo//-macro +([[:alnum:]_])}?( )"
cf foo -J 12345 -z keepme keepme2
+([[:alnum:]_])
matches one or more letters, numbers, or _
, which I assume to be the definition of a macro name. ?( )
removes the optional trailing space following a macro name. (Optional in the sense that a final -macro
won't have a space after it.)
Upvotes: 2
Reputation: 290495
If you want to remove all the blocks of -macro WORD
, just say so:
$ sed 's/\s-macro \S*//g' <<< "cf foo -J 12345 -z -macro TEST_IFDEFINE -macro THIS -macro THIS1 -macro THIS2" | cat -vet -
cf foo -J 12345 -z$
\s-macro \S*
matches space
+ -macro
+ space + a word
.sed 's/something//g'
removes this something
as many times as it occurs in the string.Upvotes: 3