below is Small script which took two input
- File Name
- Column name
and it will duplicate mention column
Below is Script
echo "Enter CSV File name "
read fileName
echo "Enter Column name to be duplicated "
read columnName
columnNumber=`head -1 $fileName | awk -v RS="," "/$columnName/{print NR;}"` #Identify Column number using column name
totalNumberOfColumn=`head -1 $fileName | awk -F',' '{print NF}'` #identify total number of column
str="" #Create empty variab str to print column number in awk
for ((i=1;i<=$totalNumberOfColumn;i++));
do
str="$str \$$i\",\""
if [ $i == $columnNumber ]
then
str="$str \$$i\",\""
fi
done
awk -F',' "{print ${str}}" $fileName | sed 's/,$//g' #Print all column inculding duplicate column
below is content of file, file name is data.csv
:cat data.csv
Name, Surname, City, Age, Job
John, Doe, Johannesburg, 28, Technical Support
Output 1 for Duplicating column City
:bash script.sh
Enter CSV File name
data.csv
Enter Column name to be duplicated
City
Name, Surname, City, City, Age, Job
John, Doe, Johannesburg, Johannesburg, 28, Technical Support
Output 2 : for Duplicating column Name
:bash script.sh
Enter CSV File name
data.csv
Enter Column name to be duplicated
Name
Name,Name, Surname, City, Age, Job
John,John, Doe, Johannesburg, 28, Technical Support