Reputation: 5167
I am trying to use sed to extract some assignments being made in a text file. My text file looks like ...
color1=blue
color2=orange
name1.first=Ahmed
name2.first=Sam
name3.first=
name4.first=
name5.first=
name6.first=
Currently, I am using sed to print all the strings after the name#.first's ...
sed 's/name.*.first=//' file
But of course, this also prints all of the lines with no assignment ...
Ahmed
Sam
# I'm just putting this comment here to illustrate the extra carriage returns above; please ignore it
Is there any way I can get sed to ignore the lines with blank or whitespace only assignments and store this to an array? The number of assigned name#.first's is not known, nor are the number of assignments of each type in general.
Upvotes: 1
Views: 571
Reputation: 185254
sed -n 's/^name[0-9]\.\w\+=\(\w\+\)/\1/p' file
Ahmed
Sam
-n
switch suppress the default behavior of sed
: printing all liness///
is the skeleton for a substitution^
match the beginning of a linename
literal string[0-9]
a digit alone\.\w\+
a literal dot (without backslash means any character) followed by a word character [a-zA-Z0-9_] al least one : \+
( )
is a capturing group and \1 is the captured groupUpvotes: 1
Reputation: 246877
This is a slight variation on sputnick's answer:
sed -n '/^name[0-9]\.first=\(.\+\)/ s//\1/p'
The first part (/^name[0-9]\.first=\(.\+\)/
) selects the lines you want to pass to the s///
command. The empty pattern in the s
command re-uses the previous regular expression and the replacement portion (\1
) replaces the entire match with the contents of the first parenthesized part of the regex. Use the -n
and p
flags to control which lines are printed.
Upvotes: 2