views:

68

answers:

6

I'm trying to get this script to basically read input from a file on a command line, match the user id in the file using grep and output these lines with line numbers starting from 1)...n in a new file.

so far my script looks like this

#!/bin/bash
linenum=1
grep $USER $1 |
while [ read LINE ]
do
echo $linenum ")" $LINE >> usrout
$linenum+=1
done

when i run it ./username file i get

line 4: [: read: unary operator expected

could anyone explain the problem to me?

thanks

+1  A: 

Leave off the square brackets.

while read line; do
  echo $linenum ")" $LINE
done >> usrout
Pointy
missing the linenum increment :)
vladr
+3  A: 

Just remove the [] around read line - they should be used to perform tests (file exists, string is empty etc.).

Paolo Tedesco
i just found this out, thanks
KP65
+3  A: 

How about the following?

$ grep $USER file | cat -n >usrout
Greg Bacon
+1  A: 

just use awk

awk -vu="$USER" '$0~u{print ++d") "$0}' file

or

grep  $USER file |nl

or with the shell, (no need to use grep)

i=1
while read -r line
do
 case "$line" in
  *"$USER"*) echo $((i++)) $line >> newfile;;
 esac
done <"file"
ghostdog74
A: 

Why not just use grep with the -n (or --line-number) switch?

$ grep -n ${USERNAME} ${FILE}

The -n switch gives the line number that the match was found on in the file. From grep's man page:

-n, --line-number
      Prefix  each  line of output with the 1-based line number
      within its input file.

So, running this against the /etc/passwd file in linux for user test_user, gives:

31:test_user:x:5000:5000:Test User,,,:/home/test_user:/bin/bash

This shows that the *test_user* account appears on line 31 of the /etc/passwd file.

Jim
A: 

Also, instead of $foo+=1, you should write foo=$(($foo+1)).

Steve Emmerson