Since nobody has posted one yet, here are a few Perl solutions:
perl -ne 's/.*con.*="(.+)".*/$1/ && print' file
Explanation
The -ne
means "Read the input file line by line and apply the script passed by -e
". The s/foo/bar/
is the substitution operator, it will replace foo
with bar
. In this case, the replacement will be whatever was matched in the parentheses, this is $1
. The regex means "match everything up to con
, then the longest string until a =
and then capture everything between the quotes. The && print
will print the modified line only if the replacement was successful.
perl -e 'print grep{s/.*con.*=.(.+)".*/$1/}<>' file
Explanation
This one is a bit more idiomatic. It will print the result of applying the same substitution as used above to each line of the input file (<>
). Just a different way of writing the same basic approach.
perl -F'[="]' -lane 'print $F[5] if $F[2]=~/con/' file
Explanation
The -a
makes perl
behave like awk
, it automatically splits the input line into fields (saved as the @F
array) on the character(s) passed by the -F
parameter. Since I tell it to split on =
or "
, the 5th field will be what we're after and it is only printed if the 2nd field matches con
. The -l
adds a newline to each print
call (and other things that are not relevant).
And here's another grep
one. This will print all matches of letters/letters
, it works correctly on your example but might not on a more complex one:
grep -Eio '[a-z]+/[a-z]+' file
And a pure shell one (bash/zsh/ksh):
while IFS='=' read a b c; do
[[ "$b" =~ "con" ]] && a=${c/%?\/>/} && echo ${a/#?};
done < file
Explanation
The while read; do ... ; done < file
loops through each line of the file. Setting IFS
to =
splits each line at =
and read a b c
saves each field in the variables $a
through $c
. Then, if $b
matches con
, the last three characters are removed from $c
and the result is saved as $a
and then printed with the first character (the quote) removed. See here for more on bash's string manipulation options.
xmlstarlet
orxmllint
. stackoverflow.com/questions/91791/…cut -d '"' -f4
?