I normally use Perl when things get too hard for sed and grep.
There are a number of ways you could write it in Perl. For example, you might prefer it to be fast, or you might prefer it to handle slight unexpected problems in the input (e.g. two spaces where one was expected).
One obvious way (assumes id is numeric, city is alphabetic, status is alphabetic):
while (<>) {
if (/^\[\d+\] (\w+(?: \w+)*), \w+ \(\w*\)$/) {
my $city = $1;
print "$city\n";
}
}
Or slower but more permissive (does more backtracking):
while (<>) {
if (/^.*\]\s+(.*),.*$/) {
my $city = $1;
print "$city\n";
}
}
Or faster (field stops at first occurrence of closing bracket):
while (<>) {
if (/^\[[^]]*\] ([^,]*), \S+ \([^)]*\)$/) {
my $city = $1;
print "$city\n";
}
}
From the command line rather than a script, you could use the -n
option, which basically adds the while (<>) { BLOCK }
loop:
perl -ne '/^\[[^]]*\] ([^,]*), \S+ \([^)]*\)$/ and print $1, "\n";' cities
or if you want the usage to resemble cut, you can use the -F
option, which is similar to awk's -F
option, for example:
perl -a -n -F'/[],]\s+/' -e 'print $F[1], "\n"' cities
This way obviously assumes that no field will contain any of the delimiters.
tr
is useful for deleting characters you don't want.(inactive)
status or not? Please provide sample output.cut
to cut things out and you can see the intent of the failed example I have, it should be fairly clear in the context. I will provide sample out though to clear it up further. :)