Swap of fields dynamically

Dear Friends,

I have file a.txt

1|2|3|4|5|6|7|8
a|b|c|d|e|f|g|h

i am using the below code to swap the fields in file

awk -F\| '{print $5,$1,$2,$3,$4,$6,$7,$8}' OFS=\| a.txt > output.txt

output.txt

5|1|2|3|4|6|7|8
e|a|b|c|d|f|g|h

The above command is working fine. I am trying make it dynamic for swpping the field.I am struck where and how to start .My inputs should be the which column should come in first field and rest moving other side .Please find example for the above file

 
Swapfields.sh a.txt 5 8 
5= First field in putputfile
8=number of fields.

Plz help.

Hi

$ awk -v x=5 '{printf $x; for(i=1;i<=NF;i++)if(i!=x)printf "|%s",$i;print "";}' FS="|"  file
5|1|2|3|4|6|7|8
e|a|b|c|d|f|g|h

Guru.

1 Like

Without any validations:

awk -F\| -v first=5 -v num=8 '{
printf "%s", $first
for(i=1;i<=num;i++)
 if(i!=first)
  printf "|%s",$i
printf "\n"
}' file
1 Like

This is my script. name is test.sh

$ cat test.sh
file=$1 #file name
FIR=$2 # first field to print
FILD=$3 # Number of fields

awk -v first="$FIR" -v Field="$FILD" -F "|" '{ s=$first; for(i=1;i<=Field;i++){if(i != first){s=s"|"$i}}{print s}}' $file
$ sh test.sh file 6 7
6|1|2|3|4|5|7
f|a|b|c|d|e|g

$ sh test.sh file 5 8
5|1|2|3|4|6|7|8
e|a|b|c|d|f|g|h

$ cat file
1|2|3|4|5|6|7|8
a|b|c|d|e|f|g|h
1 Like

@Guru. Thanks for the quick response. it is working as expected. I have used the same in my script . :slight_smile: :slight_smile:

---------- Post updated at 05:18 PM ---------- Previous update was at 05:12 PM ----------

@elixir,Pamu. Thanks for the reply. Your solution works perfect :slight_smile: :slight_smile: Need to learn more from You all and this forum makes me to learn and share my knowledge :slight_smile: :slight_smile: