LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   array - passing values to sed command (https://www.linuxquestions.org/questions/linux-newbie-8/array-passing-values-to-sed-command-749248/)

casperdaghost 08-21-2009 04:46 AM

array - passing values to sed command
 
i grep this file and had to delete some of the results with sed - it worked fine

casper@kops11>egrep "cancel|modify|submit" evntlog.89655.Fri | sed -e '/Confirm/d' -e '/Third/d' -e '/find/d' -e '/Local/d' -e '/Auto/d' -e '/GEcp/d' -e '/BookConnectSServer/d' -e '/ExecReport/d'

just for investigation sake - i piped the grep results into a different file and then i tried to create a simple array loop that would sed out the line one by one out of the new file - is there a way to pass values to sed?

casper@kops11> vi simplearray
casper@kops11> more simplearray
#!/bin/sh

names=( Confirm Third find Local Auto GEcp BookConnectSServer ExecReport )
$(names[@])

for name in $(names[@])
do
sed '/"$name"/d' evntlog2.89655.Fri
done

casper@kops11> chmod +x simplearray
casper@kops11> simplearray
simplearray: line 4: names[@]: command not found
simplearray: line 9: names[@]: command not found

zhjim 08-21-2009 04:59 AM

Quote:

Originally Posted by casperdaghost (Post 3652120)
casper@kops11> more simplearray
#!/bin/sh

names=( Confirm Third find Local Auto GEcp BookConnectSServer ExecReport )
$(names[@])

for name in $(names[@])
do
sed '/"$name"/d' evntlog2.89655.Fri
done

casper@kops11> chmod +x simplearray
casper@kops11> simplearray
simplearray: line 4: names[@]: command not found
simplearray: line 9: names[@]: command not found

The $( command ) part tells bash to run the string inside the brackets as a command. So right now your telling bash to run a variable as a command.
Either leave out the $( ) part or use $( echo names[@] ).


Cheers Zhjim

rizhun 08-21-2009 05:09 AM

Or, do it in Perl:

IgnoreKeywords.pl:
Code:

#!/usr/bin/perl -w

my @names = ("Confirm", "Third", "find", "Local", "Auto", "GEcp", "BookConnectSServer", "ExecReport");

while (<STDIN>) {
  chomp;
  my $match = 0;

  foreach $name (@names) {
    if ( $_ =~ m/$name/ ) { $match++ }
  }

  if ( $match == 0 ) { print $_, "\n" }
}

Execution:
Code:

$ < evntlog.89655.Fri IgnoreKeywords.pl

konsolebox 08-21-2009 05:43 AM

Quote:

Originally Posted by casperdaghost (Post 3652120)
for name in $(names[@])

perhaps that should be
Code:

for name in "${names[@]}"
if you're going to read from a file it should be:
Code:

for name in $(<file)
or
Code:

while read name; do
  ...
done < file

or
Code:

# if you're going to read standard input
while read -u 4 name; do
  ...
done 4< file



All times are GMT -5. The time now is 10:32 PM.