I have a strign in bash with the following format:
// comment.
I want to obtain a new variable with comment alone (no backslash) and I don't want to depend on the // begin the first two characters in the string. How can I do this?
I have tried this:
nline=${line/%/////}
echo $nline
To use string substitution but it doesn't work.
Perhaps you want the #
substitution?
$ a='// this is a comment'
$ printf "%s\n" "${a#// }"
this is a comment
$ a='not a comment'
$ printf "%s\n" "${a#// }"
not a comment
And as SergA pointed out, a little better patterns for our variable extraction can save us the need for the sed solution below:
$ a="first //a comment"
$ printf "%s" "${a##*//}"
If you just want to get the comment part of a line anywhere it is you could use sed
like so:
$ a="first //a comment"
$ printf "%s\n" "$a" | sed -e 's,^.*// \?,,'
a comment
which of course you could store in another variable:
nline=$(printf "%s" "$a" | sed -e 's,^.*// \?,,')
(note also that I remved the \\n
from the printf
)
删除前两个字符:
echo ${nline:2}
%
matches the end of the string. #
matches the beginning of the string.
Since you said you wanted neither of those you don't want either %
or #
in there.
Also you need to escape /
in a /
-delimited pattern.
nline=${line/\/\/}
echo "$nline"
This will remove the first //
from the string no matter where it is or what comes before it. So foo // comment
will become foo comment
, etc.
If you want to also remove any surrounding spaces from the //
string then you need to do a bit more work and can't so easily use string substitution for it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.