0

I have a line like below from a file finalinput.txt

Apr 9, 2021 10:52:35 PM EDT c1d99c1af08ce4ae:-4277b446:178b8700262:-8000-0000000000019a8b 1618023155272 I wrote a small code subtest.sh below

keyinput="c1d99c1af08ce4ae:-4277b446:178b8700262:-8000-0000000000019a8b"

for line in $(cat finalinput.txt)
do
if $line | grep "$keyinput" > /dev/null; then
 echo -e "$date $time\n" >> timeoutput.txt
fi
done

output :
 line 20: Apr: command not found
./subtest.sh: line 20: 9,: command not found
./subtest.sh: line 20: 2021: command not found
./subtest.sh: line 20: 10:52:35: command not found
./subtest.sh: line 20: PM: command not found
./subtest.sh: line 20: EDT: command not found
./subtest.sh: line 20: c1d99c1af08ce4ae:-4277b446:178b8700262:-8000-0000000000019a8b: command not found
./subtest.sh: line 20: 1618023155272: command not found
./subtest.sh: line 20: ###Update: command not found
./subtest.sh: line 20: Assignment: command not found
./subtest.sh: line 20: Milestone: command not found
./subtest.sh: line 20: Apr: command not found
./subtest.sh: line 20: 9,: command not found
./subtest.sh: line 20: 2021: command not found
./subtest.sh: line 20: 10:52:37: command not found
./subtest.sh: line 20: PM: command not found
./subtest.sh: line 20: EDT: command not found

please help where i am wrong

sravani srinija
  • 73
  • 1
  • 1
  • 7

1 Answers1

0

You should first fix the obvious shellcheck mistakes:

Line 1:
keyinput="c1d99c1af08ce4ae:-4277b446:178b8700262:-8000-0000000000019a8b"
^-- SC2148: Tips depend on target shell and yours is unknown. Add a shebang or a 'shell' directive.
 
Line 3:
for line in $(cat finalinput.txt)
            ^-- SC2013: To read lines rather than words, pipe/redirect to a 'while read' loop.
 
Line 6:
 echo -e "$date $time\n" >> timeoutput.txt
          ^-- SC2154: date is referenced but not assigned (for output from commands, use "$(date ...)" ).
                ^-- SC2154: time is referenced but not assigned (for output from commands, use "$(time ...)" ).

While fixing SC2013 read https://mywiki.wooledge.org/BashFAQ/001 . Read about when to use quoting in shell When to wrap quotes around a shell variable? .

where i am wrong

The $line executes a command with the name resulting from the expansion of variable line. You want to pass the content of line variable as input to grep. You want:

if echo "$line" | grep "$keyinput" > /dev/null; then

but it's better to:

if printf "%s\n" "$line" | grep -q "$keyinput"; then

Overall in bash you can:

if grep -q "$keyinput" <<<"$line"; then

and pragmatically the whle script is just reading lines from file... that's what grep does anyway.

if grep "$keyinput" finalinput.txt; then

Also echo -e ....\n is just the same as echo .....

KamilCuk
  • 120,984
  • 8
  • 59
  • 111