Printing $values using awk


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Printing $values using awk
# 8  
Old 11-15-2015
Your first specification didn't mention you want a subset of the column, and your revision had a mismatch between the ctrl file and the data file's header. Having taken care for this, try
Code:
awk -F\| '
FNR == NR       {HD[NR] = $0
                 MXCOL = NR
                 next
                }
FNR == 1        {for (n=1; n<=NF; n++)
                   for (h in HD)  if ($n == HD[h])      {{COL[h] = n
                                                         break
                                                        }
                }
                {DL = ""
                 for (c=1; c<=MXCOL; c++) if (COL[c])   {printf "%s%s", DL, $(COL[c])
                                                         DL = FS
                                                        }
                 printf "\n"
                }
' ctrl source
ename|eid|esal
peter|10|$2000
shaun|11|$1000

# 9  
Old 11-15-2015
Does this help:
Code:
awk '	# Name interpreter to be used and start the script to be run.
BEGIN {	# Set input and output field separators before we read any input files.
	FS = OFS = "|"
}
FNR == NR {
	# When the number of records read from the current file (FNR) is the
	# same as the number of records read from all files (NR), we are reading
	# data from the control file.
	# For each line read, set the heading data array indexed by the desired
	# heading data to the output field position for this heading.  (The
	# output field position is also the current number of lines read from
	# the control file.)
	hd[$0] = ++hc
	# Skip to next input line without processing later actions in this
	# script.
	next
}
FNR == 1 {
	# When we read the 1st line of the data file, look at each heading...
	for(i = 1; i <= NF; i++)
		# If the heading is an index in the hd[] array...
		if($i in hd)
			# Set the output field order array indexed by the
			# desired output order to the input field number to be
			# printed in that field.
			of[hd[$i]] = i
}
{	# For all lines in the data file print the desired input fields in the
	# order in which they are supposed to appear in the output file...
	for(i = 1; i <= hc; i++)
		# Print the desired field and the output field separator (when
		# the loop variable does not indicate the last time through the
		# loop) or the output record separator (if the loop variable
		# does indicate the last time through the loop).
		printf("%s%s", $of[i], i == hc ? ORS : OFS)
}' ctrl2 source	# End the script and name the two input files.

This User Gave Thanks to Don Cragun For This Post:
# 10  
Old 11-15-2015
Hi.

Using command csvtool:
Code:
#!/usr/bin/env bash

# @(#) s1	Demonstrate extraction from CSV file, csvtool.

# Utility functions: print-as-echo, print-line-with-visual-space, debug.
# export PATH="/usr/local/bin:/usr/bin:/bin"
LC_ALL=C ; LANG=C ; export LC_ALL LANG
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
db() { ( printf " db, ";for _i;do printf "%s" "$_i";done;printf "\n" ) >&2 ; }
db() { : ; }
C=$HOME/bin/context && [ -f $C ] && $C csvtool

FILE1=data1
FILE2=data2

pl " Input source file $FILE1:"
cat $FILE1

pl " Input control file $FILE2:"
cat $FILE2

pl " Expected output:"
cat expected-output.txt

pl " Transformed control file:"
tr '\n' ',' < $FILE2 |
sed 's/,$//' |
tee data3

# Duplicate first line, so that names are transferred.
sed -n -e '1p' -e '1,$p' $FILE1 > f1

pl " Results:"
csvtool namedcol "$( cat data3 )" -t '|' -u '|' f1

exit 0

producing:
Code:
$ ./s1

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian 5.0.8 (lenny, workstation) 
bash GNU bash 3.2.39
csvtool - ( /usr/bin/csvtool, 2008-05-22 )

-----
 Input source file data1:
ename|eid|emanger|esal|ecity|deptid|deptname
peter|10|larry|$2000|melbourne|20|electronics
shaun|11|Peter|$1000|sydney|20|electronics

-----
 Input control file data2:
ename
eid
esal
ecity

-----
 Expected output:
ename|eid|esal|ecity
peter|10|$2000|melbourne
shaun|11|$1000|sydney

-----
 Transformed control file:
ename,eid,esal,ecity
-----
 Results:
ename|eid|esal|ecity
peter|10|$2000|melbourne
shaun|11|$1000|sydney

Command csvtool is available in Debian-related repositories by that name.

A generic version: https://forge.ocamlcore.org/projects/csv/

In RedHat related repositories:
Code:
Name        : ocaml-csv
Arch        : x86_64
Version     : 1.1.7
Release     : 6.2.el6
Size        : 149 k
Repo        : base
Summary     : OCaml library for reading and writing CSV files
URL         : http://merjis.com/developers/csv
License     : LGPLv2+
Description : This OCaml library can read and write CSV files, including all
            : extensions used by Excel - eg. quotes, newlines, 8 bit characters
            : in fields, quote-0 etc.
            : 
            : The library comes with a handy command line tool called csvtool
            : for handling CSV files from shell scripts.

A similar command is CSVfix

Best wishes ... cheers, drl
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Array not printing values if used in a loop

Hello! I'm making an English to Morse Code translator and I was able to mostly get it all working by looking through older posts here; however, I have one small problem. When I run it it's just printing spaces for where the characters should be. It runs the right amount of times, and if I try... (3 Replies)
Discussion started by: arcoleman10
3 Replies

2. Shell Programming and Scripting

Printing null values in awk

Hi, I have a csv file with given details abc.txt 123,ra,point,,there 232,ba,points,home,pheer I want to get those values and store them in different variables: Code: while read line do echo $line |awk -F"," '{print $1" "$2" "$3" "$4" "$5"}'|read dbt_acct val_dt crncy AMT... (11 Replies)
Discussion started by: rahulsk
11 Replies

3. UNIX for Dummies Questions & Answers

Printing the intermediate integer values

Dear Help, I have an input file which looks like - 121 300 122 345 124 567 127 234 $1 has 125 and 126 missing. How can I output those missing values? Thanks (6 Replies)
Discussion started by: Indra2011
6 Replies

4. Shell Programming and Scripting

Awk: Comparing arguments with in line values of file and printing the result

I need to develop a script where I will take two date arguments as parameter date1 and date2 which will in format YYYYMM. Below is the input file say sample.txt. sample.txt will have certain blocks starting with P1. Each block will have a value 118,1:TIMESTAMP. I need to compare the... (7 Replies)
Discussion started by: garvit184
7 Replies

5. Programming

Printing values from a class

I have a class and want to print values in MOD using L = new Layer* ; How can I print the values in MOD using this object L??? class Layer { public : Model* MODP; Model* MODS; (1 Reply)
Discussion started by: kristinu
1 Replies

6. UNIX for Dummies Questions & Answers

Printing all the values in the middle of two columns

Hi, I have a tab delimited text file with three columns: Input: 1 25734 25737 1 32719 32724 1 59339 59342 1 59512 59513 1 621740 621745 For each row of the text file I want to print out all the values between the second and third columns, including them. The... (3 Replies)
Discussion started by: evelibertine
3 Replies

7. Programming

Printing float values in C

Hi, I have small problem to print float value in the fallowing code float Cx, W,f=250000, Cr=92.00,pi=3.14; W=2*pi*f; Cx = 1/W.Cr; //Cx value will be come around like 7.07E-9. printf("capacitance value: %.10f",Cx); I am trying to print Cx value using above code but it was not... (3 Replies)
Discussion started by: veerubiji
3 Replies

8. Shell Programming and Scripting

printing two values with TAB in between

Dear friends, I want to print variables' values in certain format where space between two values of variables is "a tab" I tried where I provided "tab" between two varibales. But when it print values on screen its giving me output without spaces in two values. Request you to help me in... (7 Replies)
Discussion started by: anushree.a
7 Replies

9. UNIX for Advanced & Expert Users

Printing defaulted values

I have written a phyton script that accepts command line arguments. I am setting defaults for some of them if the user does not specify them. However I want to print the user values and the defaulted values seperately. However, once I set the default values, then I cannot use if... (0 Replies)
Discussion started by: kristinu
0 Replies

10. Programming

printing all array values using dbx 7.2.1

how do we print the entire contents of arrays in dbx ? Ive tried using print x to print values 1 to 5 of the array x, however dbx complains and doesnt allow this help is much appreciated (1 Reply)
Discussion started by: JamesGoh
1 Replies
Login or Register to Ask a Question