Discussion Locked

finding a string

0 helpful
6 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

How can create a scrippt shell using grep to look for an specific string like year in a file contaning this information

A250865|0|0|03/06/1999|03/06/1999|G|254||N|1|I|P|
A251999|315584|315584|29/05/2003|29/05/2003|N|2796|2796|N|1|I|F|

I have already did it, but it find the same string in the first column, how can I separate it,

What I need is just the information in the fourth column.

For your help thank you !!

6 replies

by ghislain.levesque

file1="your file"
cat $file | while read line
do file_date=`echo $line|cut -d"|" -f4`
echo "Here is your date : "$file_date
done

It will read all line in your file and the variable file_date will have your date info for you.

by alveden

Try this

script.sh
--- begin ---
#/bin/sh
cat $1 | awk -F "|" '$4 ~ /1999/ {print $0}'
--- end ---

U can use the script by running script.sh [filename]

This will match the fourth column for year 1999 and return the whole line that match the relevant results. Modify the value 1999 to your needs and if you want to show specific colum, modify the $0 to something else like $1 to show first column, or {print $1, $5} to show column 1 and 5

by sundiego

Observation:

- You have a file which has the "Pipe" symbol <|> as
the "Field Separator".
- Field 4 and 5 are the date in the format : DD/MM/YYYY

- You didnot specify that you want to find the year 1999 in field 4 , or 5, or either, or both .

Answer:

Case 1: Look for "/1999" in either field 4 or 5:

A simple grep can do the job:

cat file_name | grep '/1999'

Explanation: the date has the forward slash in it.

Case 2: Look for "/1999" in field 4 only.

cat file_name | awk -F"|" '( $4 ~ "/1999" ) {print $0}'

Case 3: Look for "/1999" in field 5 only.

cat file_name | awk -F"|" '( $5 ~ "/1999" ) {print $0}'

Case 4: Look for "/1999" in BOTH field 4 and field 5:

cat file_name | | awk -F"|" '( $4 ~ "/1999" ) && ( $5 ~ "/1999" ) {print $0}'

Note:
{print $0} == print the whole line, replace $0 with other number if you want to print certain field only, SEPARATE them by comas.
Ex.: {print $1, $3, $5}

Good luck,

This discussion is closed to new replies.