Ubuntu, Bash 4.3.48
Hi,
I have this input file:
a1:b2:c30:g4:h12:j7
and I want this output file:
a1=g4:b2=h12:c30=j7
I can do it this with this code:
awk -F':' '{print $1"="$4":"$2"="$5":"$3"="$6"}' INPUT > OUTPUT
In this case I have 6 columns, I calculate manually the half number of columns (6/2=3) and I wrotte $1 + $4 ... $3 + $6
Now I want to update my code with one that do everything in automatic, considering that the number of columns of the input file is unknown.
Some additional codes...
1) awk -F':' '{print NF; exit}' INPUT > COUNT_NF # with this I know the number of columns
2) I need a code to do this: NF/2= hNF
(half of NF)
3) I think that for the main code I have to create a loop... like this
$1 "=" $(hNF+1)
this to repeat for hNF times (i=hNF)
example...
awk -F':' -v hNF=$hNF ' { for (i=1; i<=hNF; i++) print $1"="$(hNF+1)":" }' INPUT > OUTPUT
Could you help me please!
Thanks
You can determine hNF in awk, just before the for loop.
I don't know how... I'm not expert on this... I took the code from other sites :-/
awk -F':' '{print NF; exit}' INPUT | awk '{print $1 / 2}' > halfcount
aaa=$(cat halfcount)
awk -F':' -v bbb=$aaa '{for (i=1; i<=aaa; i++) {print ($i)"="$(aaa+$i)":"} }' INPUT > OUTPUT
does not work :-/
Here are a couple of options you could try:
awk '{hNF=NF/2; s=""; for(i=1; i<=hNF; i++) s=s (i==1?"":OFS) $i "=" $(hNF+i); print s}' FS=: OFS=: file
awk '{hNF=NF/2; for(i=1; i<=hNF; i++) printf "%s=%s%s",$i,$(hNF+i),(i<hNF)?OFS:ORS}' FS=: OFS=: file
awk '{n=split($0,F); $0=""; for(i=1; i<=n/2; i++) $i=F "=" F[i+n/2] }1' FS=: OFS=: file
1 Like
is perfect! thank you !!!
Hello echo manolis,
Following sed
solution may also help you in same in case your Input_file has 6 columns(mentioned by you in your post).
sed 's/\([^:]*\):\([^:]*\):\([^:]*\):\([^:]*\):\([^:]*\):\([^:]*\)/\1=\4:\2=\5:\3=\6/' Input_file
Output will be as follows.
a1=g4:b2=h12:c30=j7
Thanks,
R. Singh