1

I have a file which has the following form:

#id|firstName|lastName|gender|birthday|creationDate|locationIP|browserUsed
111|Arkas|Sarkas|male|1995-09-11|2010-03-17T13:32:10.447+0000|192.248.2.123|Midori

Every field is separated with "|". I am writing a shell script and my goal is to remove the "-" from the fifth field (birthday), in order to make comparisons as if they were numbers.

For example i want the fifth field to be like |19950911|

The only solution I have reached so far, deletes all the "-" from each line which is not what I want using sed.

i would be extremely grateful if you show me a solution to my problem using awk.

4
  • Do you want - replaced with anything ? Commented Mar 20, 2016 at 17:20
  • @ArifBurhan I want the fifth field to be like |19950911| Commented Mar 20, 2016 at 17:27
  • 2
    read about AWK's gsub function Commented Mar 20, 2016 at 17:28
  • 2
    You do not need to remove the -s since a string comparison of YYYY-MM-DD will produce the same relative order as a numeric comparison of YYYYMMDD. Commented Mar 20, 2016 at 20:47

3 Answers 3

3

If this is a homework writing the complete script will be a disservice. Some hints: the function you should be using is gsub in awk. The fifth field is $5 and you can set the field separator by -F'|' or in BEGIN block as FS="|"

Also, line numbers are in NR variable, to skip first line for example, you can add a condition NR>1

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

1 Comment

My problem is that I speek Greek and I can't find proper gsub documentation that i can understand. The homework task is only this so it is a "one-line" solution that's why I did not write the full script.
1

An awk one liner:

awk 'BEGIN { FS="|" } { gsub("-","",$5); print }' infile.txt

4 Comments

Yes that finally worked. But I want to ask one more thing. At the command you wrote if i write: awk 'BEGIN { FS="|" } { gsub("-","",$5); print $1,"|",$2 }' infile.txt The result is "Whatever $1 is" "blank" "|" "blank" "Whatever $2 is". How do i remove blank spaces?
Remove the commas: print $1 "|" $2. OR you can set OFS: BEGIN {OFS=FS="|"} {gsub...; print $1, $2}. Note that when you set OFS (output file separator) you keep the commas, but don't explicitly print the |.
That was very helpful. I appreciate it.
You can define OFS value as "|"
1

To keep "|" as output separator, it is better to define OFS value as "|" :

... | awk 'BEGIN { FS="|"; OFS="|"} {gsub("-","",$5); print $0 }'

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.