简体   繁体   中英

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
awk '{for(i=1;i<=NR-FNR;i++) print $0,i}' OFS='_' file file

之所以起作用,是因为第一次读取文件时NR-FNR始终为零,而第二次读取时它始终为26。

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

如果您对awk ,可以请尝试以下操作。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM