简体   繁体   中英

Adding new column using awk command adds the whole content to the last?

I am trying to append a current date field using awk in every line to my pipe separated content. Instead of what is intended, the whole 16 columns are getting appended to the 17th (new) position. I tried changing things but did not help. I think there is some basic mistake. Can I be helped here?

 awk ' BEGIN{FS="|";}
{
    $17=$(date +"%d-%m-%Y");

    printf("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s\n", $1, $2, $3, $4, $5, $6, $7, $8, $9, $10,
     $11, $12, $13, $14, $15, $16, $17);

}' /Users/temp/dispn/content3.txt | less > /Users/temp/dispn/content4.txt

Input(16 fields):

EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0

My Output

EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0|EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0

Intended (17 fields):

EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0|06-22-2014

I guess the problem here is that the $(date +"%d-%m-%Y"); in the script is interpreted as $0 because bash is not expanding it. To prevent this you can define the awk script in double quotes like this:

awk "{print \$0\"|\"$(date +\"%d-%m-%Y\")}"

which requires all sort of escaping $ and " characters to make it work.

If you do not need to use awk but could also use sed you could use:

sed "s/$/|$(date +"%d-%m-%Y")/"

Assign the date to a variable and print it with the entire line,

awk -F'|' -v var=$(date +"%d-%m-%Y") '{print $0,var}' OFS="|"

Example:

$ echo 'EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0' | awk -F'|' -v var=$(date +"%d-%m-%Y") '{print $0,var}' OFS="|"
EX122YED| Buy online |example.com/EX122YED |example.com/EX122YED.jpg|White|new|00.00|in stock|XYZ|Accessories|Accessories|Male|30-40|y|EX122YED|0.0|22-06-2014

If you want month-date-year format then change the date command to date +"%m-%d-%Y"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM