Home > database >  how to add 1 .txt 2.txt 3.txt 4.txt at the end of each line of file
how to add 1 .txt 2.txt 3.txt 4.txt at the end of each line of file

Time:05-10

a.txt

12
23
45
56

Expected output:

12 >1.txt
23 >2.txt
45 >3.txt
56 >4.txt

I have tried below-given this command but it's not working:

sed -i s/$/\>1.txt/ a.txt

I want to store the value 12 in the file 1.txt; 23 in 2.txt; 45 in 3.txt; and 56 in 4.txt

I am using Busybox, so I don't have Bash, and non-portable uses of Awk etc will also probably not work.

CodePudding user response:

You can use awk and increment an int for each line

awk 'BEGIN{i=1} /.*/{printf "%s >%d.txt\n",$0,i; i  }' a.txt

CodePudding user response:

Using sed

$ n=1; while read -r line; do sed s"/.*/echo & > $n.txt/e" <<< $line;n=$((n 1)); done < a.txt
$ cat 1.txt
12

CodePudding user response:

This might work for you (GNU sed & expr):

sed -n 'x;s/.*/expr &   1/e;x;/\S/G;s/\(.*\)\n\(.*\)/echo "\1" >\2.txt/e' file

Store a counter in the hold space and increment it for each line input.

Append the counter to the current line and then format an expression to store the current line in a file designated by the counter and evaluate it.

CodePudding user response:

If your actual question is how to write each line to a new file, try

awk 'NR>1 { close(f) }
    { f=  n ".txt"; print >f }' a.txt

Demo: https://ideone.com/a65wFT (IdeOne runs on Linux but I have separately tested this on BusyBox v1.34.1 (2021-12-29 21:12:15 UTC))

If you can't get Awk to work, try

n=0
while read -r line; do
    echo "$line" >"$((  n)).txt"
done <a.txt

Perhaps see also split; however, the Busybox split appears to have limited support for controlling the generated output file names.

  • Related