0

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
4
  • 1
    the tag [shell] is generic, and doesn't tell us what implementation you are using. Most likely [bash], so please add a tag for your shell of preference. Search your shell's documentation for math operations. Good luck. Commented Jul 11, 2019 at 12:13
  • You can mention that A..Z are example values, you don't want printf "%s\n" {A..Z}_{01..26}. Commented Jul 11, 2019 at 13:04
  • mywiki.wooledge.org/DontReadLinesWithFor Commented Jul 11, 2019 at 14:05
  • Another nit-pick: but the use of backticks is discouraged. It's legacy, and non-POSIX. There's a number of reasons why the $() notation is preferred see some here Commented Jul 11, 2019 at 15:02

3 Answers 3

1
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

4 Comments

Ans is almost correct but I need is A_01...A_26...Z_01..Z_26
No. bro Same result like this showing A_1...A_26 want A_01
@ArunSolomon, Give it sometime and when you have few answers, you could select anyone of them as correct one too. I saw your profile and realize that you don't do that often, cheers and happy learning.
Not my downvote, but the wc -l strikes me as inelegant. You can store the file in memory, or read the file twice, and solve this in pure Awk.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.