0

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

0

6 Answers 6

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

How about the following?

$ grep $USER file | cat -n >usrout

Comments

1

Leave off the square brackets.

while read line; do
  echo $linenum ")" $LINE
done >> usrout

1 Comment

missing the linenum increment :)
1

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"

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.