![]() |
|
|
|
|
|||||||
| Forums | Portal | Register | Forum Rules | FAQ | Contribute | Members List | Arcade | Search | Today's Posts | Mark Forums Read |
| UNIX for Dummies Questions & Answers If you're not sure where to post a UNIX or Linux question, post it here. All UNIX and Linux newbies welcome !! |
|
|
Submit Tools | LinkBack | Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
awk help
I have 2 questions.
1. Using awk how do I specify two different actions based on the value of the first field on every record in a file. 2. How do I ask awk to output the current date as the last field on some records. Here is the situation. if the value of the first field is 1, I need to print the entire record and today's date otherwise print just the record. I am trying this on HP UX 11 Thanks in advance for any help. |
| Forum Sponsor | ||
|
|
|
#2
|
||||
|
||||
|
There are two ways. You can specify two pattern/action pairs...
Code:
awk -v date=$(date +%d-%b-%Y) '
$1 == 1 {
print $0, date
}
$1 != 1 {
print $0
}
' file1 > file2
Code:
awk -v date=$(date +%d-%b-%Y) '
{
if ($1 == 1) {
print $0, date
}
else {
print $0
}
}
' file1 > file2
|
|
#3
|
|||
|
|||
|
Thank you so much for the reply.
Yogr, I tried the code from the command prompt and it worked, but I think you could have your scripts in a file and specify -f option in the awk command to run against it. I tried to put the code within the quote in a file and I tried but didn't work. Any thoughts? |
|
#4
|
||||
|
||||
|
Gee thanks for the -f tip. I wonder why it didn't work when you changed it. Perhaps it was something you did?
|
|
#5
|
|||
|
|||
|
Take a look at this. This is my awk command file, florida.awk
$1 == 1 { print $0, date } $1 != 1 { print $0 } and this is how I run the command $ awk -v date=$(date +%m/%d/%y) -f florida.awk florida.txt >output I am getting the output but without the date. Do you see any problem? Thanks. |
|
#6
|
|||
|
|||
|
Yogr, forget about my previous post. I found out the problem. I didn't mention the field delimiter, I should have given the command like this,
$ awk -F"," -v date=$(date +%m/%d/%y) -f florida.awk florida.txt >output That brings another question. Using -F flag I assume we are refering the field delimiter for the input file. It is not putting the delimiter in the output file. Where or how do you specify delimiter for the output file? Thanks again for the help. |
|
#7
|
||||
|
||||
|
You can set the field separators in the BEGIN action, e.g...
BEGIN { FS=OFS="," } |
||||
| Google The UNIX and Linux Forums |