Codcz
Codcz

Reputation: 13

Create TXT file from array in Bash

I have an array of list and a file file1.txt , I want to create e new file order according to numbers in file1.txt, for example code output must be like below. How should I make it work correctly

newfile.txt 9 Z A C

but script gives me newfile.txt 2 3 4 9

file1.txt's content is like below random numbers 2 3 4 1

list=("Z" "A" "C" 9)

while read line
do
for i in ${list[@]};do

sed  "${line}s/.*/${i}/" file1.txt > newmfile.txt

done

done < "file1.txt"

Upvotes: 0

Views: 373

Answers (3)

user14473238
user14473238

Reputation:

Your file1.txt contains the mapping:

$ nl file1.txt
     1  2
     2  3
     3  4
     4  1

where the line numbers in the above output should be replaced by the contents of your array, and reordered according to the number from the file.

Here is one method, assuming none of the array elements contain newline characters:

list=("Z" "A" "C" 9)

printf '%s\n' "${list[@]}" | paste file1.txt - | sort -nk1,1 | cut -f2-

This uses paste, sort, cut to decorate-sort-undecorate. Output:

9
Z
A
C

Upvotes: 1

Raman Sailopal
Raman Sailopal

Reputation: 12867

The main issues with the script is that the sed statement needs /../ around $line. Without this, sed will do the substitution on the line number and will not search for the line. Also, as the changes aren't being retained in the original file1.txt file, only the last change takes place. You will therefore need to use the sed -i flag to execute the changes on the actual file as opposed to redirecting the changes. Additionally, having two loops is inefficient. Just use a counter and reference the elements of the array with the counter:

#!/bin/bash
list=("Z" "A" "C" 9)
cp file1.txt newmfile.txt
cnt=0
while read line 
do
   sed -i "/${line}/s/.*/${list[$cnt]}/" newmfile.txt
   cnt=$(($cnt+1))
done < "file1.txt"

Upvotes: 2

Jake Cope
Jake Cope

Reputation: 63

The number nine is the value of the for loop $i. the for loop continues 4 times as you've declared it to run to each item in the array.

for i in ${list[@]} 

uses number of items in array of

list=("Z" "A" "C" 9)

What is the end goal for what you want to achieve in the new text file? because it seems you're trying to base the number from the file1.txt on the array? If you just wanted to copy the contents of the old file to a new one - could be achieved easily with echo or cat. But I'm guessing that's not what you're after.

Upvotes: 0

Related Questions