Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Bash Script Parameters with grep 1

Status
Not open for further replies.

moria6

MIS
Jul 11, 2000
30
0
0
US
I'm trying to pass text with a space (in this case a date,e.g. Jan 20) as a parameter to grep in a shell script.


tst.sh filename.txt Jan 20 # where $1 is filename.txt, $2 is Jan 20



#!/bin/bash

cat $1 | grep $2

grep err's out with grep: 20: No such file or directory

Can anyone suggest a method to make this work, please?

I've tried quotes, brackets, etc. I've looked at bash special parameters but still can't wrap what's left of my brain around what's probably trivial.

I could do a sed / awk search and replace on the date to turn it from Jan 20 to 0120 which I know how to deal with but I'd like to learn how to work with a "block of chars
with embedded spaces" as a parm for the next time that it comes up. ;)

TIA!

maurie
 
The shell puts different words in different positional parameters. It breaks up the command line using whitespace characters found in the shell variable IFS (usually space, tab, newline)

If you want to have a positional parameter loaded with a string with embedded blanks, you need to use quotes in the command line:

[tt]tst.sh filename.txt "Jan 20"[/tt]

then inside the script like you wrote:

[tt]cat $1|grep "$2"[/tt]

but you don't need that "kitty" really (and beware of the UOOC police in this forum ;-)):

[tt]grep "$2" $1[/tt]



HTH,

p5wizard
 
Thanks, p5wizrd!

Works perfectly.

Also thanks for the feline tip. I am subjecting that text file to 10 other |'d "contortions" (various sed & awk manipulations) the first of which is an awk statement to swap a couple of fields hence the four-legged startup.

I will gradually try to clean up the script so as to avoid those UOOC chaps in the future.

Thanks again!

maurie
 
So you're cat-ing a file and then |'ing the data int one awk, into a sed, into another awk, into whatever, into yet another awk, ...

First of all, awk can read a file too

[tt]awk '{awk-pgm-1}' /path/to/input | sed 'sed-cmd-1' | awk '{awk-pgm-2}' | sed 'sed-cmd2' | sed 'sed-cmd-3'[/tt]

so that takes care of kitty yet again.

Then, consecutive sed programs can be combined into one

[tt]awk '{awk-pgm-1}' /path/to/input | sed 'sed-cmd-1' | awk '{awk-pgm-2}' | sed 'sed-cmd2;sed-cmd-3'[/tt]

Plus, if you can write it in sed, I'll bet you can write it in awk:

[tt]awk '{big awk pgm}' /path/to/input[/tt]

See the man page for awk to find out what it can do... Then try and come up with something you think awk can't do (that sed can) and I'll have a go at it... ;-)


HTH,

p5wizard
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top