Arun Solomon
Arun Solomon

Reputation: 421

shell scripting single for loop how to get a output from a file

Source file data.txt

A
B
.
.
.
Z

Source file contain A to Z write each character in one line each.

Result Need

A_01
A_02
.
.
.
A_26
B_01
.
.
B_26
.
.
.
Z_01
.
.
Z_26

Note: from the source file we need to count the no.of line and add that number to each split character.

I got a Solution But I need to do in one for statement.

end=`wc -l data.txt | awk '{print $1}'`

for i in $(cat data.txt )
do
  for j in `seq $end`
  do
    echo "$i"_"$j"
  done 
done

Upvotes: 0

Views: 85

Answers (3)

RavinderSingh13
RavinderSingh13

Reputation: 133458

If you are ok with awk, could you please try following.

awk -v line=$(wc -l < Input_file) '{for(i=1;i<=line;i++) printf("%s_%02d\n",$0,i)}' Input_file

Upvotes: 0

ceving
ceving

Reputation: 23814

Bash has a function called mapfile, to read a file in an array.

mapfile -t data < data.txt
numbers=($(seq -f '%02.0f' "${#data[@]}"))
for line in "${data[@]}"; do
  printf "${line}_%s\n" "${numbers[@]}"
done

Upvotes: 1

kvantour
kvantour

Reputation: 26471

awk '{for(i=1;i<=NR-FNR;i++) print $0,i}' OFS='_' file file

The reason this works is because NR-FNR is always zero for the first read of the file, while it is always 26 for the second read of the file.

Upvotes: 1

Related Questions